User-defined literals (since C++11)
From cppreference.com
This section is incomplete |
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.
[edit] Syntax
return decl operator"" name ( unsigned long long n ) { body }
|
|||||||||
return decl operator"" name ( long double d ) { body }
|
|||||||||
return decl operator"" name ( char c ) { body }
|
|||||||||
return decl operator"" name ( const char* str, size_t sz ) { body }
|
|||||||||
return decl operator"" name ( const char* cstr ) { body }
|
|||||||||
[edit] Explanation
return | - | Return value |
decl | - | Declaration specifier sequence, can contain keywords as constexpr or inline |
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 |
[edit] 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;
Output:
0x123ABC