Namespaces
Variants
Views
Actions

User-defined literals (since C++11)

From cppreference.com
< cpp‎ | language
Revision as of 04:10, 6 December 2013 by D41D8CD98F (Talk | contribs)

 
 
C++ language
General topics
Flow control
Conditional execution statements
if
Iteration statements (loops)
for
range-for (C++11)
Jump statements
Functions
Function declaration
Lambda function expression
inline specifier
Dynamic exception specifications (until C++17*)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
const/volatile
decltype (C++11)
auto (C++11)
constexpr (C++11)
consteval (C++20)
constinit (C++20)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Memory allocation
Classes
Class-specific function properties
explicit (C++11)
static

Special member functions
Templates
Miscellaneous
 

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'