Namespaces
Variants
Views
Actions

User-defined literals (since C++11)

From cppreference.com
 
 
C++ language
General topics
Preprocessor
Comments
Keywords
ASCII chart
Escape sequences
History of C++
Flow control
Conditional execution statements
Iteration statements
Jump statements
Functions
function declaration
lambda function declaration
function template
inline specifier
exception specifications (deprecated)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
decltype specifier (C++11)
Specifiers
cv specifiers
storage duration specifiers
constexpr specifier (C++11)
auto specifier (C++11)
alignas specifier (C++11)
Literals
boolean literals
nullptr (C++11)
user-defined (C++11)
Expressions
alternative representations
Utilities
Types
typedef declaration
type alias declaration (C++11)
attributes (C++11)
Casts
implicit conversions
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
C-style and functional cast
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
class template
function template
template specialization
parameter packs (C++11)
Miscellaneous
Inline assembly
 

C++11 introduced the ability to add custom suffixes to literals in order to provide different values. Literal suffixed 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