在 C++ 中是否可以根据模板参数包含/排除成员变量?
这是一个例子:
template< class T >
class RealNumber
{
T real;
};
template< class T >
class ComplexNumber
{
T real;
T imag;
};
因为它们有许多共同的属性,所以只有一个类来表示一个数字(带有额外的模板参数)可能会避免一些代码重复。
我想做的是类似
template< class T , class U >
Number
{
T real;
// If U is not void
U imag;
}
因此,如果第二个参数为空,则不会有名为 imag 的成员,产生:
sizeof( Number< T , void > ) == sizeof( T )
我尝试了 enable_if 但没有得到任何结果。
如果这不可能,是否有任何黑客可以使这成为可能?
最佳答案
typedef NullType struct {} NullType;
template< class T , class U = NullType>
class Number
{
T real;
U image;
}
关于c++ - 根据模板参数在编译时安排类结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8117181/