smead
smead

Reputation: 175

Using enums from a class (C++)

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

Answers (4)

TonyK
TonyK

Reputation: 17114

Two solutions:

  1. Live with it.
  2. #define AnyNumber TGNumberFormat::kNEAAnyNumber

*Runs for cover...*

Upvotes: 0

Trevor Hickey
Trevor Hickey

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

James McNellis
James McNellis

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

Roddy
Roddy

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

Related Questions