在 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;
}
因此,如果第二个参数为 void,则不会有名为 imag 的成员,产生:
sizeof( Number< T , void > ) == sizeof( T )
我尝试了 enable_if 但没有得到任何结果。
如果这是不可能的,是否有任何黑客可以使这成为可能?