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

Vin*_*ent 27 c++ templates metaprogramming enable-if c++11

请考虑以下代码:

template<bool AddMembers> class MyClass
{
    public:
        void myFunction();
        template<class = typename std::enable_if<AddMembers>::type> void addedFunction();

    protected:
        double myVariable;
        /* SOMETHING */ addedVariable;
};
Run Code Online (Sandbox Code Playgroud)

在此代码中,模板参数AddMembers允许在类中添加函数true.为此,我们使用了std::enable_if.

我的问题是:数据成员变量是否可能(可能有技巧)?(以这种方式,MyClass<false>将有1个数据成员(myVariable),MyClass<true>并将有2个数据成员(myVariableaddedVariable)?

Jam*_*lis 26

可以使用条件基类:

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

template <bool AddMembers> class MyClass
    : std::conditional<AddMembers, BaseWithVariable, BaseWithoutVariable>::type
{
    // etc.
};
Run Code Online (Sandbox Code Playgroud)


Ker*_* SB 23

首先,你的代码不会编译MyClass<false>.该enable_if特征对于推导出的参数很有用,而不适用于类模板参数.

其次,这是你如何控制成员:

template <bool> struct Members { };

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

template <bool B> struct Foo : Members<B>
{
    double y;
};
Run Code Online (Sandbox Code Playgroud)