我有一个C ++类的混合,其中一些存储状态变量0..9作为整数,其他使用'0'...'9'。 目前我这样做:
enum { kOne = '1' }; class StoresValueAsInt { static int value; // contains 0 ... 9 }; class StoresValueAsChar { static char value; // contains '0' ... '9' }; class StoresValueAsChar { static char value; }; template <typename X> isOne() { return X::value == kOne; }这允许我编写错误的代码isOne<StoresValueAsInt::value>() 。 相反,我想让编译器抱怨这种不正确的用法。 我尝试了以下方法:
enum ValueInt { kOne = 1 }; enum ValueChar { kOne = '1' }; class StoresValueAsInt { static ValueInt value; }; class StoresValueAsChar { static ValueChar value; }; class StoresValueAsChar2 { static ValueChar value; };但是,这不起作用,因为kOne在命名空间级别是可见的,因此它具有冲突的kOne声明。
有没有办法不在命名空间中声明枚举? 或者更好的方法吗?
更新:添加了我目前所做的事情; 希望澄清我的用例。
I have a mixture of C++ classes, some of which store a state variable 0..9 as integer, others use '0' ... '9'. Currently I do:
enum { kOne = '1' }; class StoresValueAsInt { static int value; // contains 0 ... 9 }; class StoresValueAsChar { static char value; // contains '0' ... '9' }; class StoresValueAsChar { static char value; }; template <typename X> isOne() { return X::value == kOne; }This allows me to write the buggy code isOne<StoresValueAsInt::value>(). Instead, I would like to have the compiler complain about this incorrect usage. I tried the following:
enum ValueInt { kOne = 1 }; enum ValueChar { kOne = '1' }; class StoresValueAsInt { static ValueInt value; }; class StoresValueAsChar { static ValueChar value; }; class StoresValueAsChar2 { static ValueChar value; };However, this does not work, because kOne is visible at the namespace level, and thus it has conflicting declarations of kOne.
Is there a way to not have the enums declared in the namespace? Or a better approach here?
updated: Added what I currently do; hoping to clarify my use case.
最满意答案
就最佳实践而言,我真的不确定你要在这里完成什么,所以我不能指出你正确的方向。
但是,要直接回答您的问题:将枚举放在单独的命名空间中可以解决您的问题:
namespace IntVals { enum ValueInt { kOne = 1 }; } namespace CharVals { enum ValueChar { kOne = '1' }; } class StoresValueAsInt { static ValueInt value; }; class StoresValueAsChar { static ValueChar value; };然后你应该能够使用以下内容:
StoresValueAsInt::value == CharVals::kOne虽然这很丑陋,但我希望我能更好地理解你的目标,提供比这更优雅的解决方案。
As far as best practice, I'm really not sure what you are trying to accomplish here so I can't point you in the right direction.
However, to answer your question directly: Placing the enums in seperate namespaces would solve your issue:
namespace IntVals { enum ValueInt { kOne = 1 }; } namespace CharVals { enum ValueChar { kOne = '1' }; } class StoresValueAsInt { static ValueInt value; }; class StoresValueAsChar { static ValueChar value; };Then you should be able to use the following:
StoresValueAsInt::value == CharVals::kOneThough this is ugly, and I wish I understood better what you were going for to offer a more elegant solution than this.
更多推荐
发布评论