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

标签 c++ templates c++11 metaprogramming enable-if

考虑以下代码:

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.
};

关于c++ - 使用模板参数添加/删除数据成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12117912/

相关文章:

java - 缓存基本 XWPFDocument 模板并重用它们来生成文档

c++ - boost addable 和 dll 的辅助功能错误

c++ - 迭代单链表不工作的驱动程序

c++ - 使用 boost.asio 的免费 async_* 函数时出现奇怪的错误

c++ - 折叠表达式 : iterate over variadic template type parameter to check compile-time conditions on the comprising types

c++ - Ratio<,> 是常量,但如果我想接受不同的比率作为参数怎么办?

c++ - 我不明白 std::shared_ptr 的 -> 运算符

c++ - 类型名和范围运算符的语法错误

C++ cout打印缓慢

c++ - 使用CodeBlocks编译64位DLL会导致链接器错误