Reputation: 175
I'm using a library that has classes with a number of enums. Here's an example
class TGNumberFormat
{
public:
// ...
enum EAttribute { kNEAAnyNumber
kNEANonNegative
kNEAPositive
};
enum ELimit { kNELNoLimits
kNELLimitMin
kNELLimitMax
kNELLimitMinMax
};
enum EStepSize { kNSSSmall
kNSSMedium
kNSSLarge
kNSSHuge
};
// etc...
};
In the code I have to refer to these as TGNumberFormat::kNEAAnyNumber
for example. I'm writing a GUI that uses these values very often and the code is getting ugly. Is there some way I can import these enums and just type kNEAAnyNumber
? I don't really expect any of these names to overlap. I've tried various ways of using the using
keyword and none will compile.
Upvotes: 5
Views: 503
Reputation: 17114
Two solutions:
#define AnyNumber TGNumberFormat::kNEAAnyNumber
*Runs for cover...*
Upvotes: 0
Reputation: 37806
If your using c++11 you can use the keyword auto to deduce the type:
//the compiler will see auto and know to use: TGNumberFormat::EAttribute
auto attribute = TGNumberFormat::kNEAAnyNumber;
compiled with: g++ -std=c++0x -o main main.cpp
If you're not using c++11, consider using typedefs as mentioned by @James McNellis
using macros are not recommended because they won't obey the rules of scope-- typedefs will.
Upvotes: 0
Reputation: 355019
If you are using these constants all over in your code, it might be beneficial to create your own header that redefines the values in a namespace. You can then using
that namespace. You don't need to redefine all of the values, just the names of the enumerators. For example,
namespace TGEnumerators
{
static EAttribute const kNEAAnyNumber(TGNumberFormat::kNEAAnyNumber);
// etc.
}
Alternatively, you can typedef TGNumberFormat
to a shorter name in the functions or source files where you use it frequently. For example,
typedef TGNumberFormat NF;
NF::EAttribute attribute = NF::kNEAAnyNumber;
I'd argue that the latter approach is superior, and if used judiciously at block scope, is a fine practice. However, for use across a file, I think it'd be preferable to use the full names of the enumerators, for clarity.
Upvotes: 8
Reputation: 68023
One other way that's possible but involves a bit more work up front is to define a batch of consts that you then use instead:
e.g.
const TGNumberFormat::EAttribute AnyNumber = TGNumberFormat::kNEAAnyNumber;
const TGNumberFormat::EAttribute NonNegative = TGNumberFormat::kNEANonNegative;
...
attribute = AnyNumber;
Upvotes: 0