jeudi 22 septembre 2022

Convert enum values from external library to local datatypes

I have lot of enum from external library, which I am trying to convert it to local datatypes. I do not want datatypes or header files from external library to be included everywhere in the client code.

At present I am doing something like below. Is there a better way to do this.

struct ExtServer {
  enum class Color { RED, BLACK, GREEN, ORANGE };
  enum class Fruit { ORANGE, APPLE };
};

struct Wrapper {
  enum class Color { RED, BLACK, GREEN, ORANGE };
  enum class Fruit { ORANGE, APPLE };
  
  template<typename T, typename U> 
  T convert(U value) { return static_cast<T>(value); }
  
  Color From(ExtServer::Color color) {
    return convert<Color, decltype(color)>(color);
  }
  Fruit From(ExtServer::Fruit fruit) {
    return convert<Fruit, decltype(fruit)>(fruit);
  }
};

struct Client {
  void do_something() {
    Wrapper obj;
    obj.From(ExtServer::Color::RED);
    obj.From(ExtServer::Fruit::APPLE);
  }
};
  
int main() {
    Client client;
    client.do_something();
}

Aucun commentaire:

Enregistrer un commentaire