在C++11中,我想在一个类中有一个成员变量,并且只有在选择了它的默认模板值时才有构造函数进行初始化(当然仅对支持的类型如int)。
有哪些推荐的方法可以实现这一点(允许使用boost)?
类似于:
```cpp template class MyClass { //... private: T member_; }; ```
或者换一种说法:为了进行尺寸和速度优化,如果选择了模板默认值之外的另一个值,则我希望使用编译时常量而不是存储在成员变量中的值。
--
这里有一个例子,让一切都更清晰:
这部分解决了问题:
有哪些推荐的方法可以实现这一点(允许使用boost)?
类似于:
```cpp template class MyClass { //... private: T member_; }; ```
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
的构造函数呢?还有其他更好的解决方案吗?
B
有三个专业化方向?我知道这并不是很可扩展,但它取决于您使用案例的许多细节...恐怕我不知道任何简单而通用的解决方案。 - Daniel Frey