使用模板参数添加/删除数据成员?

36

考虑以下代码:

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个数据成员(myVariableaddedVariable)?

2个回答

37

可以使用条件基类:

struct BaseWithVariable    { int addedVariable; };
struct BaseWithoutVariable { };

template <bool AddMembers> class MyClass
    : std::conditional<AddMembers, BaseWithVariable, BaseWithoutVariable>::type
{
    // etc.
};

34

首先,你的代码无法编译 MyClass<false>enable_if 特性适用于 推导出的 参数,而不适用于类模板参数。

其次,以下是如何控制成员变量的方法:

template <bool> struct Members { };

template <> struct Members<true> { int x; };

template <bool B> struct Foo : Members<B>
{
    double y;
};

+++++1太棒了!使用有条件的模板参数进行混合 - Viet
1
我发现这个答案比被接受的答案更好,谢谢! - mojo1mojo2
记住这个观点的一个简单方法是:“enable_if特性对于推断的参数非常有用,而不适用于类模板参数。”template <bool AddMem = AddMembers> typename std::enable_if<AddMem>::type addedFunction();将在AddMembers = false时消除编译时错误。 - Hari

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接