[英]Shorten path to C++ enum member (using typedef or typename), to use as template parameter
I have a rather complicated object, 我有一个相当复杂的对象,
MyNamespace::MyClass::MySubStruct
which has an 有一个
enum
{
ONE = 1,
TWO = 2
};
Now I have another class which has a template parameter 现在我有另一个具有模板参数的类
template <unsigned int x> class Foo;
Currently I initialize B as follows 目前我按如下方式初始化B.
Foo<MyNamespace::MyClass::MySubStruct::ONE> MyFoo
and that works just fine, but it is a bit too lengthy, especially given that I initialize this class about a hundred times. 这很好,但它有点太冗长,特别是考虑到我将这个类初始化了大约一百次。
I would like to write something like: 我想写一些类似的东西:
typedef MyNamespace::MyClass::MySubStruct::ONE MyONE
Foo<MyOne> MyFoo
Naturally, this does not compile, and neither does declaring it as a const unsigned int inside the class. 当然,这不会编译,也不会将它声明为类中的const unsigned int。 How would one do this elegantly?
如何优雅地做到这一点?
Enumerators are values, not types. 枚举器是值,而不是类型。 If you only need this particular enumerator, declare a constant:
如果您只需要这个特定的枚举器,请声明一个常量:
const auto MyONE = MyNamespace::MyClass::MySubStruct::ONE;
If you need more than only this one, it could be feasible to add a typedef for MySubStruct
and access the enumerators through that. 如果您需要的不仅仅是这个,那么为
MySubStruct
添加typedef并通过它访问枚举器是可行的。
ONE
isn't a type; ONE
不是一种类型; it's a value. 这是一个价值。
Instead of using typedef
, you could simply use a constant: 您可以简单地使用常量:而不是使用
typedef
:
const auto MyONE = MyNamespace::MyClass::MySubStruct::ONE;
Consider also using enum class
instead of enum
. 还要考虑使用
enum class
而不是enum
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.