C++ 使用模板参数添加/删除数据成员?
考虑以下代码:C++ 使用模板参数添加/删除数据成员?,c++,templates,c++11,metaprogramming,enable-if,C++,Templates,C++11,Metaprogramming,Enable If,考虑以下代码: template<bool AddMembers> class MyClass { public: void myFunction(); template<class = typename std::enable_if<AddMembers>::type> void addedFunction(); protected: double myVariable; /*
template<bool AddMembers> class MyClass
{
public:
void myFunction();
template<class = typename std::enable_if<AddMembers>::type> void addedFunction();
protected:
double myVariable;
/* SOMETHING */ addedVariable;
};
模板类MyClass
{
公众:
void myFunction();
模板void addedFunction();
受保护的:
双变量;
/*可加变量的事物;
};
在这段代码中,模板参数AddMembers
允许在类为true
时向类添加函数。为此,我们使用std::enable_if
我的问题是:对于数据成员变量,是否也有相同的可能(可能有一个技巧)?(以这样的方式,
MyClass
将有1个数据成员(myVariable
)和MyClass
将有2个数据成员(myVariable
和addedVariable
)?可以使用条件基类:
struct BaseWithVariable { int addedVariable; };
struct BaseWithoutVariable { };
template <bool AddMembers> class MyClass
: std::conditional<AddMembers, BaseWithVariable, BaseWithoutVariable>::type
{
// etc.
};
struct BaseWithVariable{int addedVariable;};
结构basewithout变量{};
模板类MyClass
:std::conditional::type
{
//等等。
};
首先,您的代码不会为MyClass
编译。enable\u if
特性对推导参数有用,而不是类模板参数
其次,以下是控制成员的方法:
template <bool> struct Members { };
template <> struct Members<true> { int x; };
template <bool B> struct Foo : Members<B>
{
double y;
};
模板结构成员{};
模板结构成员{int x;};
模板结构Foo:成员
{
双y;
};
+1完美!与条件模板参数混合我发现这比公认的答案要好,谢谢!