使用模板参数添加/删除数据成员? [英] Add/Remove data members with template parameters?

查看:75
本文介绍了使用模板参数添加/删除数据成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

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.

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.

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

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

推荐答案

可以使用条件基类:

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

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

这篇关于使用模板参数添加/删除数据成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆