Templates 在模板类中有条件地包含成员

Templates 在模板类中有条件地包含成员,templates,c++11,Templates,C++11,我想根据模板类的模板参数的值排除或包括模板类中的一些成员。下面是一个例子: enum t_chooser {A, B, all}; template <t_chooser choice> class C { // include if choice==A int v1; // include if choice==B long v2; // include if choice==B int v3; // includ

我想根据模板类的模板参数的值排除或包括模板类中的一些成员。下面是一个例子:

enum t_chooser {A, B, all};

template <t_chooser choice>
class C {

    // include if choice==A
    int v1;
    // include if choice==B
    long v2;
    // include if choice==B    
    int v3;
    // include for every value of choice
    bool v4;
};
如果模板参数选项等于all,则应包括所有成员。 在C++11中有没有实现这一点的方法,甚至可以使用std::enable_if


我在这里看到了一种成员函数的解决方案:

显然,您可以为每种类型的t\u选择器专门化整个C类,但这是一种痛苦,因为您必须复制所有内容。相反,您可以将专门化放入helper结构中,然后在C中派生它


显然,您可以为每种类型的t_选择器专门化整个C类,但这是一种痛苦,因为您必须复制所有内容。相反,您可以将专门化放入helper结构中,然后在C中派生它


如果可以在方法中包含/排除使用这些变量的代码行,也很有意思,即编写一个适用于所有模板值的方法,类似于ifdef宏。您可以TMP大多数类似的内容,但您需要帮助。也很有意思的是,如果可以在使用这些变量的方法中包括/排除代码行,即编写适用于所有模板值的方法,类似于ifdef宏。您可以TMP大多数类似的内容,但需要帮助。
enum t_chooser {A, B, all};

template <t_chooser choice>
struct Vars; // undefined

template<>
struct Vars<A> { // just the A vars
  int v1;
};

template<>
struct Vars<B> { // just the B vars
  long v2;
  int v3;
};

template<>
struct Vars<all> : Vars<A>, Vars<B> { }; // derive both, get everything

template <t_chooser choice>
class C : private Vars<choice> { // or public if you want to expose them
    bool v4;
};