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?
isValid()functionstatic, and change thelegalValue()function to doreturn S::isValid(e);, and I think this should compile...legalValue<Enum>()should work for anyenumthat has an associatedisValid()function. It doesn't work for enums nested withclassorstruct.struct S { enum E; bool foo(E); }; struct T { enum F; bool foo(F); };. You want a template that will do the "correct" thing given eitherS::EorT::F?In my case, the natural home is inside a struct: Then try putting the function outside the struct, with its parameter beingS::Einstead of plainE.