考虑以下代码:
template<bool AddMembers> class MyClass
{
public:
void myFunction();
template<class = typename std::enable_if<AddMembers>::type> void addedFunction();
protected:
double myVariable;
/* SOMETHING */ addedVariable;
};
在这段代码中,模板参数AddMembers
允许在类中添加函数 true
.为此,我们使用 std::enable_if
.
我的问题是:数据成员变量是否同样可能(可能有技巧)? (这样 MyClass<false>
将有 1 个数据成员( myVariable
)和 MyClass<true>
将有 2 个数据成员( myVariable
和 addedVariable
)?
最佳答案
可以使用条件基类:
struct BaseWithVariable { int addedVariable; };
struct BaseWithoutVariable { };
template <bool AddMembers> class MyClass
: std::conditional<AddMembers, BaseWithVariable, BaseWithoutVariable>::type
{
// etc.
};
关于c++ - 使用模板参数添加/删除数据成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12117912/