成员变量和构造函数(取决于模板参数)

Tho*_*mas 5 c++ templates constructor member c++11

在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
};
Run Code Online (Sandbox Code Playgroud)

或者,换一种说法:对于大小和速度优化,如果选择了不同于模板默认值的另一个值,我想使用编译时间常数而不是存储在成员变量中的值。

-

这是使所有内容更清晰的示例:

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!
};
Run Code Online (Sandbox Code Playgroud)

这可以部分解决:

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()
};
Run Code Online (Sandbox Code Playgroud)

但是的构造函数C呢?还有其他/更好的解决方案可用吗?

Dan*_*rey 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!
  }
};
Run Code Online (Sandbox Code Playgroud)

但正如我所说,这只是一个主意...