jeudi 1 octobre 2020

Variable enum 'class' in c++

I use something like in the following code fairly often:

// myclass.h

class MyClass {
 public:
  enum MyEnum { E1, E2, NUMMYENUM };
  const char* kMyEnum[NUMMYENUM] = {"e1", "e2"};
  const char* MyEnum2Char(MyEnum me) { return kMyEnum[me]; }

  enum MySEnum { SE1, SE2, NUMMYSENUM };
  static const char* kMySEnum[NUMMYSENUM];
  static const char* MySEnum2Char(MySEnum se) { return kMySEnum[se]; }

  void foo(MyEnum me) {
    //do something, e.g. print
    std::cout << MyEnum2Char(me) << "maps to " << emap[me] << "\n";
  }

  void bar(MySEnum se) {
    //do something, e.g. print
    std::cout << MySEnum2Char(se) << "maps to " << semap[se] << "\n";
  }

 private:
  std::map<MyEnum, int> emap;
  std::map<MySEnum, int> semap;
 };


// myclass.cc

#include "myclass.h"

const char* MyClass::kMySEnum[MyClass::MySEnum::NUMMYSENUM] = {"se1", "se2"};

The way of generating an enum, a char* array and a function converting enum to char seems to add avoidable clutter and I am wondering if there isn't another way to achieve this? Something like the following isn't possible for multiple reasons, but might give you an idea of what I'd like to have:

// myclass.h

class MyClass {
 public:
  MyVariableEnumClass MyEnum(E1, "e1", E2, "e2");    
  static MyVariableEnumClass MySEnum;

  void foo(MyEnum me) {
    //do something, e.g. print
    std::cout << me.string() << "maps to " << emap[me] << "\n";
  }

  void bar(MySEnum se) {
    //do something, e.g. print
    std::cout << se.string() << "maps to " << semap[se] << "\n";
  }

 private:
  std::map<MyEnum, int> emap;
  std::map<MySEnum, int> semap;
 };


// myclass.cc

#include "myclass.h"

MyVariableEnumClass MyClass::MySEnum = MyVariableEnumClass(SE1, "se1", SE2, "se2");

Is there a way to achieve something 'clutter-free' like this? Maybe using Macros?

Aucun commentaire:

Enregistrer un commentaire