c++ - 根据模板参数声明成员或不声明成员

标签 c++ templates c++11

不使用dummy empty类型,是否可以根据模板条件声明或不声明成员变量?

例子:

struct empty{};
struct real_type{};

template<bool condition>
struct foo
{
    typename std::conditional<condition, real_type, empty>::type _member;
};

最佳答案

您可以从具有特化的模板派生:

struct real_type { };

template<bool c>
struct foo_base { };

template<>
struct foo_base<true>
{
    real_type _member;
};

template<bool condition>
struct foo : foo_base<condition>
{
};

作为一个小测试:

int main()
{
    foo<true> t;
    t._member.x = 42; // OK

    foo<false> f;
    f._member.x = 42; // ERROR! No _member exists
}

关于c++ - 根据模板参数声明成员或不声明成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16673169/

相关文章:

php - 关键未捕获错误 : Call to a member function is_on_sale() on null in Woocommerce

c++ - 使用std::sort对C风格的2D数组进行部分排序

c++ - bool 数据类型在 C++ 中是可移植的吗?

c++ - 命名等价和结构化等价之间的区别?

c++ - 如何将元组转换为初始值设定项列表

c++ - 了解此 `const&` 特化的必要性

c++ - vector move 构造函数比复制构造函数慢

c++ - gcc/c++ v2.96 上不存在 wstring

c++ - FLTK版本1.3.2,Visual Studio 2012和Stroustrup的PPP书的第一个示例

c++ - 引用作为参数的模板参数推导