【问题标题】:Conditionally include members in template class有条件地在模板类中包含成员
【发布时间】:2015-07-24 22:11:39
【问题描述】:

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

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

如果模板参数choice 等于all,则应包括所有成员。 有没有办法在 C++11 中实现这一点,甚至可以使用std::enable_if

我在这里看到了成员函数的解决方案:std::enable_if to conditionally compile a member function

【问题讨论】:

  • 如果可以在使用这些变量的方法中包含/排除代码行,即编写一个适用于所有模板值的方法,类似于#ifdef 宏。
  • 你可以 TMP 大多数这样的事情,但你需要帮助。

标签: templates c++11


【解决方案1】:

显然,您可以为每种类型的t_chooser 专门化整个C 类,但这很痛苦,因为您必须复制所有内容。相反,您可以将专业化放入辅助结构中,然后在 C 中派生它

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

【讨论】:

    猜你喜欢
    • 2023-01-21
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多