私は、任意の、おそらく負のストライドを処理できるカスタム配列スライス クラスを作成しようとしています。
#include <vector>
#include <cstdio>
template< typename T >
class ArrayView
{
public:
ArrayView( void* pointer, int strideInBytes, int length )
{
m_pPointer = reinterpret_cast< unsigned char* >( pointer );
m_strideInBytes = strideInBytes;
m_length = length;
}
const T& operator [] ( int index ) const
{
const unsigned char* p = m_pPointer + index * m_strideInBytes;
return *( reinterpret_cast< const T* >( p ) );
}
T& operator [] ( int index )
{
unsigned char* p = m_pPointer + index * m_strideInBytes;
return *( reinterpret_cast< T* >( p ) );
}
int length() const
{
return m_length;
}
private:
unsigned char* m_pPointer;
int m_strideInBytes;
int m_length;
};
void printFromReadOnlyView( const ArrayView< int >& view )
{
for( int i = 0 ; i < view.length(); ++i )
{
printf( "%d: %d\n", i, view[i] );
}
}
void useRef( std::vector< int >& ref )
{
// works fine
ArrayView< int > view( ref.data(), sizeof( int ), ref.size() );
printFromReadOnlyView( view );
}
void useConstRef( const std::vector< int >& constRef )
{
// const error
ArrayView< int > view( constRef.data(), sizeof( int ), constRef.size() );
printFromReadOnlyView( view );
}
int main()
{
std::vector< int > v( 10 );
for( int i = 0; i < v.size(); ++i )
{
v[i] = i;
}
useRef( v );
useConstRef( v );
}
関数 useConstRef() は、constRef.data() が const ポインターであり、ArrayView のコンストラクターが非 const ポインターを受け取るため、コンパイル時エラーになります。
基本的に、ArrayView を const (読み取り専用) または非 const (読み取り/書き込み) にする必要があります。
代わりに、const ポインターを受け取るコンストラクターを追加してみることができますが、その場合、const ポインターを保存して、自分がどのバージョンであるかを覚えておく必要があります。1 つのクラスだけを使用して問題を解決できますか? それとも、ReadWriteArrayView と ReadOnlyArrayView のバージョンを別々に作成する必要がありますか?