枚举作为模板
这就是我想要做的:
enum MyEnum
{
ONE = 1, TWO, THREE
};
template<class T>
void func()
{
cout << T::TWO << endl;
}
int main()
{
func<MyEnum>();
};
它有效,但我收到警告:“警告 C4482:使用非标准扩展:在限定名称中使用 enum 'MyEnum'”
我怎样才能在不收到警告的情况下执行此操作
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
枚举在这里有点棘手。类型 ONE 和 TWO 将位于外部命名空间中。
因此,将类型添加到名称中会导致警告。
您可以删除限定符,
因为这两个在外部命名空间中是已知的。
您也可以将枚举移动到某种封闭结构中。
现在编译器应该没问题了。
Enum is a little tricky here. The type ONE and TWO will be in the outer namespace.
So adding the type to the name results in the warning.
You could just remove the qualifier
Since the TWO is known in the outer namespace.
You could also just move your enum to some sort of enclosing struct.
Now the compiler should be fine.
枚举(C++0x 之前的版本)被视为整型。
事实上,符号 MyEnum::TWO 是垃圾:没有类或命名空间 MyEnum。名称 ONE、TWO 和 THREE 被带入定义枚举的命名空间 [在本例中为全局命名空间]。
您应该收到类似
TWO is not a member of MyEnum
的错误。模拟该行为的一种方法是将其放入结构或类中,就像其他人建议的那样。
Enums (pre C++0x) are treated like integral types.
In fact, the notation MyEnum::TWO is garbage: there is no class or namespace MyEnum. The names ONE, TWO, and THREE are brought into the namespace where the enum is defined [in this case, the global namespace].
You should get an error like
TWO is not a member of MyEnum
.One way to emulate the behavior is to put it in a struct or class, like others have suggested.
虽然使用枚举作为模板参数并让它在编写时单独识别每个单独的枚举会很好,但这种情况不会发生。相反,我可以建议您声明以下内容:
C++ 的伟大之处在于模板的构造方式为您提供了一个完整的车削系统。因此,您不需要像这样的单独调用,因为您已声明获取每个单独的枚举值。您可以在需要时且仅在需要时为每个值创建单独的函数。
现在,回到您问题的另一个问题,正如 @delnan 评论的那样,您不能有两个具有相同名称的不同枚举。但是,您可以拥有一个带有名为
TWO
成员变量的类,这样:希望有所帮助。
While it would be nice to use the enum as the template parameter and have it recognize each individual enum separately as you've written it, it won't happen. Instead, may I suggest that you declare the following:
The great thing about C++ is that the way templates are structured gives you a Turning complete system. Hence, you don't need a separate call like this, as you've declared to get each individual enum value. You can create a separate function for each value when you need it and only when you need it.
Now, getting to the other problem of your question, as @delnan commented, you can't have two different Enums with the same name. You can, however, have a class with a member variable called
TWO
such that:Hope that helps.