I have a pretty old application using different types of currencies. At the moment, currencies are stored in a transfer, for example:
enum CURRENCY {
EUR,
USD,
CNY
};
double convertMoney(CURRENCY in, CURRENCY out, double money_in) {
...
}
This works great, but it's actually not safe: I have other functions containing comments, such as WARNING: all inputs should have the same currency. My goal is to replace most of these comments with compile-time checking whenever possible. I can use C ++ 17 and increment.
I thought to use std::variantto:
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};
...
...
return 0;
}
But, of course, this will not work, since I'm trying to insert objects of different types into the vector of Market objects.
, , , , enum ++? std::variant , ?
, :
- -
using Markets = std::variant<Market<EUR,USD>,Market<EUR,CNY>,...>, , 100 , . CURRENCY EUR, USD, CNY CURRENCY, v- , . - , , .- ( ), .