声明成员与否取决于模板形参
Declaring member or not depending on template parameter
是否可以根据模板条件声明成员变量而不使用虚拟空类型?
的例子:
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
}
是否可以根据模板条件声明或不声明成员变量而不使用虚拟空类型?
我相信你也可以专门化而不需要派生。这在-std=c++03
和-std=c++11
下都测试正常。
template<bool condition>
struct foo;
template<>
struct foo<true>
{
real_type _member;
};
template<>
struct foo<false>
{
};
如果c++委员会给我们想要/需要的东西,那就太好了:
template<bool condition>
struct foo
{
#if (condition == true)
real_type _member;
#endif
};
相关文章:
- 使用mem_fun_ref if成员函数需要多个形参
- 通过类的模板形参特化成员模板结构
- 非类型引用形参/实参
- 哪个模板形参在boost::shared_ptr构造函数中使用一个原始指针
- 如何确保迭代器模板形参与模板类的模板形参具有相同的数据类型
- 如何在编译时通过模板形参默认值的名称/指针获取函数的类型
- c++:候选模板被忽略:模板形参显式指定的参数无效
- c++中作为形参的指针
- 哪种方法更适合为函数提供编译时间常数?函数实参与模板形参
- 包含void*结构的函数的Const正确性和形参
- 传递boost::函数,该函数接受一个模板实参作为默认为NULL的形参
- 将右值引用形参强制转换为右值引用
- 给引用形参赋值使对象无效
- 当实参是初始化列表而形参是引用时,重载解析
- const整型模板形参的条件
- 使用作为模板形参提供的基类成员,不带限定符
- 模板类的不同返回类型取决于类的形参
- 模板形参有二义性:无法推断模板实参
- 声明成员与否取决于模板形参
- 非类型形参取决于它后面的实参