5

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どうですか?他の/より良い解決策はありますか?

4

3 に答える 3

5

単なるアイデアですが、役立つかもしれません。基本クラスを最小限の違いにのみ使用し、メンバー変数が存在しない場合にメンバー変数を「偽造」して、残りをコンパイルできるようにすることができます。

template< int _x > class B
{
public:
  B() {}
protected:
  static const int x = _x;
};

template<> class B< -1 >
{
public:
  B( int i ) : x( i ) {}
protected:
  int x;
};

template< int _x = -1 >
class C : public B<_x>
{
public:
  using B<_x>::B; // inherit B's ctors

  void f()
  {
    if ( x == ... ) // uses either the member variable x or the static const int x!
  }
};

しかし、私が言ったように、それは単なるアイデアです...

于 2013-04-08T19:15:48.057 に答える
2

専門化は進むべき道です:

template <int N> struct C
{
    C(int n) : n_(n) { }
    int n;
};

template <> struct C<-1>
{
    C() { }
    C(int n) : n_(n) { }
    int n;
};
于 2013-04-08T18:09:25.373 に答える