C++嵌套枚举的操作
我有几个类似于以下内容的嵌套枚举。我希望定义一个尽可能接近 enum
定义的 isValid()
函数。实际代码更加冗长,具有多层嵌套命名空间和结构。
struct S
{
enum E { V1, V2 };
/* ????? */ bool isValid(E e) { return e==V1 || e==V2; }
};
template <typename Enum>
bool legalValue(Enum e)
{
return isValid(e);
}
是否可以使此代码工作而不必将 isValid()
放在全局命名空间中?
请不要评论 isValid()
是否是好的做法。这个问题同样适用于想要重写运算符<<()以便能够有意义地流式传输枚举值的人。那么,有什么方法可以将operator<<()的本质定位到struct S的主体中呢?
I have several nested enums similar to the following. I want to have an isValid()
function defined as close as possible to the enum
definition. Actual code is more verbose with multiple levels of nested namespaces and structs.
struct S
{
enum E { V1, V2 };
/* ????? */ bool isValid(E e) { return e==V1 || e==V2; }
};
template <typename Enum>
bool legalValue(Enum e)
{
return isValid(e);
}
Is it possible to make this code work without having to place isValid()
in the global namespace?
Please don't comment on whether isValid()
is good practice. This question is just as applicable for someone wanting to override operator<<()
to be able to stream enum values meaningfully. In that case, is there any way the essence of operator<<()
can be located within the body of struct S
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,您必须将
isValid
移出struct
。不过,enum
定义可以保留在其中。No, you'll have to move
isValid
out of thestruct
. Theenum
definition can stay inside it, though.无法从
S::E
找到S
。如果
S
是一个命名空间,Koenig 查找 将找到isValid
即使它不是全局命名空间的一部分,但我认为这不是你的意思。It is not possible to find
S
fromS::E
.If
S
were a namespace, Koenig lookup would findisValid
even if it is not part of the global namespace, but I think that's not what you mean.如果这是针对标准 C++,即 C++2011,您可以转发声明嵌套枚举:
当然,您也不需要将枚举嵌套到结构中以避免污染封闭范围:相反,您可以使用
不合格的使用
V1
或V2
是非法的。If this is for standard C++, i.e. for C++2011, you could forward declare the nested enumeration:
Of course, you also wouldn't need to nest the enumeration into a struct to avoid pollution of the enclosing scope: instead you'd use
Using
V1
orV2
unqualified would be illegal.这些可能是技术点,但使
isValid
全局化的另一个选择是重载(或专门化)legalValue
。另一种选择是让
isValid
成为全球好友。尽管这与它只是一个自由的全局函数几乎没有什么不同。These might be technical points, but another option from making
isValid
global is to overload (or specialize)legalValue
.Another option is to make
isValid
a global friend. Though this differs in almost no way from it just being a free global function.