Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>

using ull = unsigned long long;

struct euro
{
    ull val;
};

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

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading