不使用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/