问题描述
如果我们有一个枚举类型:
enum E {
E1,E2,// ...
};
并基于 E
,一个类模板:
template <E T>
class C { /* ... */ };
有没有办法使用类型为 E
的声明的变量作为模板参数?
示例代码:
E example_type = E1;
C<example_type> example_class;
解决方法
对于整数(枚举是)和算术类型,实例化期间提供的模板参数必须是 constant expression。例如:
enum E {
E1,E2,};
template <E enum_val>
class Foo {
};
int main() {
constexpr E var = E1;
const E var2 = E2;
Foo<var> foo;
Foo<var2> foo2;
E var3 = E2;
Foo<var3> foo3; // error: the value of ‘var3’ is not usable in a constant expression
}