Home > database >  How to use dollar / euro sign in code to initialize a variable?
How to use dollar / euro sign in code to initialize a variable?

Time:12-22

I want to write some code that uses different types of currencies, eg

struct euro {
    int value;
};

struct dollar {
    int value;
};

Now I'd like to use the euro and dollars sign in code, something like

euro e = 3€;
dollar d = 3$;

Is this possible somehow?

CodePudding user response:

What you need is user defined lietrals. The code below worked for me using g 11.1.0 but I guess that there could be some problems with non ASCII €. Maybe try using EUR suffix? For negative values see this.

#include <charconv>
#include <cstring>
#include <iostream>
    
struct euro
{
    unsigned long long val;
};

euro operator"" _€ (unsigned long long num)
{
    return euro {num};
}

int main()
{
    euro e = 123_€;
    std::cout << e.val << '\n';
}

CodePudding user response:

You can get close to this syntax with user defined literals : Note not all compilers accept special characters but my MSVC does. Ofcourse you could make one currency class and do some kind of conversion based on exchange rates but that's up to you :)

#include <iostream>

struct dollars_t
{
    double value;
};

struct rupees_t
{
    double value;
};

constexpr dollars_t operator "" _$(long double value)
{
    return dollars_t{ static_cast<double>(value) };
};

constexpr rupees_t operator "" _₹(long double value)
{
    return rupees_t{ static_cast<double>(value) };
};


int main()
{
    auto dollars = 10.12_$;
    auto rupees = 1000.12_₹;

    std::cout << "You have " << dollars.value << " dollars\n";
    std::cout << "And you have " << rupees.value << " rupees\n";

    return 0;
}
  • Related