在编译时根据模板参数安排类结构
Arranging Class Structure at Compile Time according to Template Parameters
是否可以在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,则没有名为imagg的成员,结果是:
sizeof( Number< T , void > ) == sizeof( T )
我尝试了enable_if,但是没有得到任何结果。
如果这是不可能的,有什么hack可以使它成为可能吗?
typedef NullType struct {} NullType;
template< class T , class U = NullType>
class Number
{
T real;
U image;
}
检查继承技巧是否适合您:
template<class T, class = void >
class RealNumber
{
protected: T real;
};
template<class T, class U>
class ComplexNumber : public RealNumber<T>
{
U imag;
};
这个答案是不完整的,只展示了如何使用enable_if
来专门化类模板。
template<class T,class U,class Enable = void>
class Number
{
T real;
T imag;
};
template<class T,class U>
class Number<T,U,typename std::enable_if<std::is_void<U>::value>::type>
{
T real;
};
具体实现取决于问题的确切性质。例如,
- 如果允许RealNumber到ComplexNumber转换(即
is_a
关系),您可以考虑从一个实现继承到另一个实现。 - 要重用大量属性,可以在私有基类中实现公共部分。
- 根据具体问题,可以检查模板参数
U
是否真的需要。还有,实数Number<int,void>
或Number<int>
的首选语法应该是什么。等。
很难说你想说什么,但这里有一个大致的框架:
template <typename T> class Number
{
template <typename S> class Adder
{
typedef S type;
static type add(type a, type b) { return a + b; }
};
template <typename U, typename W> class Adder<std::pair<U,W>>
{
typedef typename std::pair<U,W> type;
static type add(type a, type b) { return type(a.first + b.first, a.second + b.second); }
};
T val;
public:
T operator+(const T rhs) { return Adder<T>::add(val, rhs); }
};
请注意,大多数标准库数值函数已经为std::complex
类型重载了,因此您可能需要考虑一下是否真的需要自己编写这些。
用法:Number<int>
, Number<double>
, Number<std::pair<double, double>>
.
相关文章:
- 使用不带参数的函数访问结构元素
- 将结构字段的类型展开为可变模板参数
- MSVC将仅移动结构参数解释为指针
- 如何使我的 sizeof sum 结构与空参数包一起工作
- 如何传递带有通过引用传递的结构参数的函数?
- 展开可变参数模板结构
- 在类构造函数中定义结构变量的参数
- 如何在方法中传递结构参数
- 我应该在C++中将这些结构用作参数化构造函数吗?
- 带参数的数据结构的全局声明
- C++ 带有默认参数的结构,可选择在构造函数中更改
- C++-将具有引用的长参数列表重构为结构
- 为私有结构定义双参数运算符重载
- 我们可以用参数化构造函数初始化结构的数组吗?
- 关于类的想法 参数结构给定实现
- 重映射模板参数结构
- 从C 调用的编译MATLAB函数的输入参数结构
- 如何实现具有不同参数结构的纯虚拟函数
- 如何在C++中获得可更改的函数参数结构
- 函数参数 -> 结构体成员的 void* 和常量 void* 的解决方案