Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

Literal Operators in C++

📅 2020-Oct-20 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cpp, literal operators ⬩ 📚 Archive

In C++, some types of literals are specified by attaching a certain suffix to them. For example, the suffix f in 3.14f specifies this as a float value, instead of the default double value.

In C++11 and later, user-defined literals are supported by means of defining literal operators.

Literal operators are functions with the name operator "" SUFFIX. Your own literal operators should use suffixes with a leading underscore, for example operator "" _BIGINT. Suffixes without a leading underscore are reserved for the standard library, for example operator "" BIGINT. But, this being C++, you are allowed to define without a leading underscore, but be prepared to see a warning from GCC (-Wliteral-suffix) and your suffix being overridden in the standard library in the future - so not a good idea.

For integer literals, the literal operator can have input to be either unsigned long long or const char*. In the latter case, the input is a null terminated string.

For string literals, the literal operator has an input of (const char *, size_t) i.e., both a pointer to the char array and its length.

What you do in the literal operator and what you return is left to you. You can cast the input, create an object from it and return it or even call a remote computer from inside - anything is allowed since it is just a function.

void operator "" _PRINT(unsigned long long x)
{
    std::cout << x;
}

BigInt operator "" _BIGINT(const char* carr)
{
    return BigInt(carr);
}

IPAddress operator "" _IP(const char* s, size_t n)
{
    return IPAddress(s, n);
}

// Usage:
1234_PRINT;
BigInt b = 123333333333333333333333333333333_BIGINT;
IPAddress s = "127.0.0.1"_IP;

© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧