[英]How can I use a enum variable as template argument?
如果我們有一個枚舉類型:
enum E {
E1,
E2,
// ...
};
並基於E
,一個 class 模板:
template <E T>
class C { /* ... */ };
有沒有辦法使用E
類型的聲明變量作為模板參數?
示例代碼:
E example_type = E1;
C<example_type> example_class;
對於整數(枚舉)和算術類型,實例化期間提供的模板參數必須是 常量表達式。 例如:
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.