Add/Remove data members with template parameters?

前端 未结 2 1833
刺人心
刺人心 2020-12-25 12:47

Consider the following code :

template class MyClass
{
    public:
        void myFunction();
        template

        
相关标签:
2条回答
  • 2020-12-25 13:16

    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;
    };
    
    0 讨论(0)
  • 2020-12-25 13:22

    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.
    };
    
    0 讨论(0)
提交回复
热议问题