Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using enums from a class (C++)

Tags:

c++

enums

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.

like image 534
smead Avatar asked Jun 12 '12 19:06

smead


1 Answers

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.

like image 84
James McNellis Avatar answered Sep 21 '22 10:09

James McNellis