Add/Remove data members with template parameters?

不想你离开。 提交于 2019-11-28 23:58:46

问题


Consider the following code :

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

    protected:
        double myVariable;
        /* SOMETHING */ addedVariable;
};

In this code, the template parameter AddMembers allow to add a function to the class when it's true. To do that, we use an std::enable_if.

My question is : is the same possible (maybe with a trick) for data members variable ? (in a such way that MyClass<false> will have 1 data member (myVariable) and MyClass<true> will have 2 data members (myVariable and addedVariable) ?


回答1:


A conditional base class may be used:

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

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



回答2:


First off, your code just won't compile for MyClass<false>. The enable_if trait is useful for deduced arguments, not for class template arguments.

Second, here's how you could control members:

template <bool> struct Members { };

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

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


来源:https://stackoverflow.com/questions/12117912/add-remove-data-members-with-template-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!