C++ 11 では、デフォルトのテンプレート値が選択された場合にのみ (もちろん int などのサポートされている型のみ)、初期化用のクラスとコンストラクターにメンバー変数が必要です。
これを達成するための推奨される方法は何ですか (ブーストは許可されています)?
何かのようなもの:
template< int _x = -1 > struct C {
C() {} // only available if _x != -1
C( int x ) : x( x ) {} // only available if _x == -1
// more methods that are common for all _x and refer to _x / x
private:
int x; // only available if _x == -1
// more members that are common for all _x
};
または、別の言い方をすれば、サイズと速度の最適化のために、テンプレートのデフォルト以外の値が選択された場合、メンバー変数に格納されている値の代わりにコンパイル時定数を使用したいと考えています。
--
すべてを明確にするための例を次に示します。
template< int _size = -1 > struct Block {
Block() { buf = mmap( _size, ... ); } // exists only when size!=-1
Block( int s ) { buf = mmap( size = s, ... ); } // exists only when size==-1
~Block() { munmap( buf, getSize() ); } // should use the correct size
int getSize() const { return ???; } // gets _size if !=-1, size otherwise
// other methods that use buf and getSize()
private:
void *buf;
const int size; // only exists for size == -1!
};
これは部分的に解決します:
template< int _x > struct X {
int getX() const { return _x; }
};
template<> struct X< -1 > {
X( x ) : x( x ) {}
int getX() const { return _x; }
private:
int x;
};
template< int _x = -1 > struct C : X< _x > {
C() {} // only available if _x != -1
C( int x ) : X< _x >( x ) {} // only available if _x == -1
// more methods that are common for all _x and use this->getX()
};
しかし、 のコンストラクターについてはC
どうですか?他の/より良い解決策はありますか?