c++ - how to get enum value from enum type? -
the question in title may sound trivial, better explain code want do...
in c++11 can this:
#include <iostream> namespace x { enum class foo { a,b }; } template <typename t> void foo(t t) { if (t == t::a) { std::cout << "a"; } } int main() { foo(x::foo::a); }
the important point here template foo
not need know in namespace enum declared. call foo(y::foo::b)
(provided there enum class
called foo
in namespace y
having members a
, b
).
now question is: how same plain old enums (and c++98 stuff)?
this works:
#include <iostream> namespace x { enum foo { a,b }; } template <typename t> void foo(t t) { if (t == x::a) { std::cout << "a"; } } int main() { foo(x::a); }
but because foo
knows in namespace enum declared. , wont work y::foo::b
! (in c++11 works if replace line if (t == t::a) ...
, plain enum
)
is there way working in c++98/03 without refering x
in template explicitly?
for sake of completeness, in c++98, this
template <typename t> void foo(t t) { if (t == t::a) { std::cout << "a"; } }
results in
error: ‘a’ not member of ‘x::foo’
ps: not allowed change enum
, template has live in different namespace enum
.
pps: simple if (t == 0)
work, thats avoid
to add nicol bolas' answer, can kind of hack way solution using adl:
namespace x { enum foo { a,b }; bool isa(foo t) { return t == a; } } template <typename t> void foo(t t) { if (isa(t)) { std::cout << "a\n"; } else{std::cout << "not a\n";} }
Comments
Post a Comment