Best way to replace an enum to maximize compilation time checks

Viewed 133

I have a rather old application dealing with different kind of currencies. For the moment, currencies are stored in an enum, for example:

enum CURRENCY {
  EUR,
  USD,
  CNY
};

double convertMoney(CURRENCY in, CURRENCY out, double money_in) {
   ...
}

This is working great, except this is not really type safe: I have other functions containing comments such as WARNING: all inputs should have the same currency. My objective is to replace most of these comments by compile time checks whenever it is possible. I can use C++17 and boost.

I thought of using an std::variant such that:

class EUR {};
class USD {};
class CNY {};

using CURRENCY = std::variant<EUR,USD,CNY>;

template<typename IN, typename OUT>
class Market {
 public:
   ...
   double convertMoney(double in) {
      return in*rate;
   }
 private:
   void updateRate() {
      ....
      rate = some_value_fetched_at_runtime;
   }
   double rate;
};

int main() {
    Market<EUR, USD> eur_usd;
    Market<EUR, CNY> eur_cny;

    std::vector<Market<CURRENCY,CURRENCY>> all_markets{eur_usd, eur_cny};
    ...
    //do something 
    ...
    return 0;
}

But of course, this won't work since I'm trying to push into my vector of Market objects with different types.

So, to sum up, what do you guys think is the best way to replace an enum in modern C++? If using std::variant is right, what would be the best way to solve the above problem?

Note that:

  1. I could do something like using Markets = std::variant<Market<EUR,USD>,Market<EUR,CNY>,...> but this is not really doable in practice since I have around ~100 type of market and this doesn't really improve maintainability.
  2. I could make a class CURRENCY and have EUR, USD, CNY child classes of CURRENCY but this would use v-table at run time which would lower the number of compile time checks. If someone can prove me the contrary, I'm open to it though.
  3. All my markets are defined in my source code (I don't need to create a new kind of market dynamically at run time), but the rate is changing dynamically.
2 Answers
Related