添加/删除具有模板参数的数据成员

Add/Remove data members with template parameters?

本文关键字:参数 数据成员 删除 添加      更新时间:2023-10-16

考虑以下代码:

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)?

可以使用条件基类:

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

首先,您的代码不会为MyClass<false>编译。enable_if特性对于推导的参数很有用,而对于类模板参数则不有用。

其次,以下是如何控制会员:

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