C++ 对于模板bool参数,使用bool类型的强枚举(C+;+;11)失败,原因是什么? enum类测试:bool{yes=true,no=false}; 模板 甲级{ }; int main(){ A A; }
为什么编译失败?(g++4.7)由于C++11枚举是强类型的,因此我们应该能够使用bool枚举作为模板类型的bool参数?强类型枚举意味着您只能隐式地比较和分配同一枚举类中的值。解决方案是使用非强类型枚举示例:C++ 对于模板bool参数,使用bool类型的强枚举(C+;+;11)失败,原因是什么? enum类测试:bool{yes=true,no=false}; 模板 甲级{ }; int main(){ A A; },c++,c++11,enums,C++,C++11,Enums,为什么编译失败?(g++4.7)由于C++11枚举是强类型的,因此我们应该能够使用bool枚举作为模板类型的bool参数?强类型枚举意味着您只能隐式地比较和分配同一枚举类中的值。解决方案是使用非强类型枚举示例: enum class test : bool { yes=true, no=false }; template< bool ok > class A { }; int main(){ A<test::yes> a; } 或者正如Tom Knapen所建议的:
enum class test : bool { yes=true, no=false };
template< bool ok >
class A {
};
int main(){
A<test::yes> a;
}
或者正如Tom Knapen所建议的:显式地强制转换枚举
enum test : bool
{
yes = true,
no = false
};
bool x = test::yes; // ok
enum类测试:bool
{
是=正确,
否=错误
};
bool x=静态(测试::是);//好啊
您需要显式转换才能将强类型枚举转换为它们的类型,这正是强类型的含义:test::yes
的类型是test
,而不是bool
,强类型枚举的全部要点是它们之间没有隐式转换。与原始版本相比,您的代码不是颠倒了test::yes
和test::no
的布尔意义吗?
enum class test : bool
{
yes = true,
no = false
};
bool x = static_cast<bool>(test::yes); // ok