33

考虑以下代码:

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

4

2 回答 2

34

可以使用条件基类:

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

template <bool AddMembers> class MyClass
    : std::conditional<AddMembers, BaseWithVariable, BaseWithoutVariable>::type
{
    // etc.
};
于 2012-08-24T23:38:06.607 回答
30

首先,您的代码不会为MyClass<false>. 该enable_if特征对推导参数有用,而不是类模板参数。

其次,您可以通过以下方式控制成员:

template <bool> struct Members { };

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

template <bool B> struct Foo : Members<B>
{
    double y;
};
于 2012-08-24T23:40:52.080 回答