C++11 introduced the ability to add custom suffixes to literals in order to provide different values.
Literal suffixes can be overloaded in a way very similar to operators.
Syntax
|
decl return operator"" name ( unsigned long long n ) { body }
|
|
|
|
decl return operator"" name ( long double d ) { body }
|
|
|
|
decl return operator"" name ( char c ) { body }
|
|
|
|
decl return operator"" name ( const char* str, size_t sz ) { body }
|
|
|
|
decl return operator"" name ( const char* cstr ) { body }
|
|
|
|
Explanation
decl
|
-
|
Declaration specifier sequence, can contain keywords as constexpr or inline
|
return
|
-
|
Return value
|
name
|
-
|
A valid C++ identifier, prefixed with an underscore. Identifiers without underscore are reserved for future use
|
n
|
-
|
Value resulting from an integral literal
|
d
|
-
|
Value resulting from a floating-point literal
|
c
|
-
|
Value resulting from a character literal
|
cstr
|
-
|
Null-terminated string as parsed by the compiler, for integer and floating point literals
|
str/sz
|
-
|
Buffer and size from a string literal
|
body
|
-
|
Function body
|
Examples
// used as conversion
inline constexpr long double operator"" _deg ( long double deg )
{
return deg*3.141592/180;
}
...
double x = 90.0_deg; // x = 1.570796
// used with custom type
struct mytype
{
...
mytype ( unsigned long long );
};
mytype operator"" _mytype ( unsigned long long n )
{
return mytype(n);
}
...
mytype x = 123_mytype;
// used for side-effects
void operator"" _print ( const char* str )
{
std::cout << str;
}
...
0x123ABC_print;//outputs '0x123ABC'