Reputation: 3405
Assume I've code like this:
namespace foo {
enum bar
{
fooBarA,
fooBarB
};
}
struct baz
{
// TODO: map "bar" in this struct to make valid:
bar returnSomething() { return fooBarA; }
};
// and also this:
void doSomething()
{
baz myBaz;
if( baz::fooBarA == myBaz.returnSomething() )
{ /* ... */ }
}
What kind of code could I put at the TODO section to make the rest valid? Some using
or typedef
?
PS: To avoid questions about the "why": The namespace is living in it's own header file and might be used by a few different classes that should agree on the values of fooBarA
and fooBarB
but also hide that they are based on foo
as that's irrelevant for the guys using baz
.
PPS: C++11 is allowed. Would enum class
help?
PPPS: Other questions like using declaration with enum? handle the case where the enum is in a class and not directly in a namespace.
Upvotes: 1
Views: 171
Reputation: 24382
This way requires a small amount of work in foo namespace. But it should be transparent to existing user of foo::bar. Just enclose your foo::bar's values in some struct from which derive your baz class:
namespace foo {
struct barValues
{
enum Values {
fooBarA,
fooBarB
};
};
typedef barValues::Values bar;
static const bar fooBarA = barValues::fooBarA;
static const bar fooBarB = barValues::fooBarB;
}
struct baz : foo::barValues
{
typedef foo::bar bar;
bar returnSomething() { return fooBarA; }
};
// and also this:
void doSomething()
{
baz myBaz;
if( baz::fooBarA == myBaz.returnSomething() )
{ /* ... */ }
if( foo::fooBarA == myBaz.returnSomething() )
{ /* ... */ }
}
Its advantage over other answer is that you enclose your foo::bar values in namespace foo - only there you add/modify/delete this enum values. This is safer I believe. Its disadvantage in comparison to other answer is that you have to modify other file which can't be an option.
Upvotes: 1
Reputation: 92231
This would work
struct baz
{
typedef foo::bar bar;
static const bar fooBarA = foo::fooBarA;
static const bar fooBarB = foo::fooBarB;
// This is now valid
bar returnSomething() { return fooBarA; }
};
but I don't know if it is really useful. If your users try to overload some functions or something, they might be in for a surprise.
Upvotes: 0