User-defined literals (since C++11)

From cppreference.com
< cpp‎ | language

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

decl return operator"" name ( unsigned long long n ) { body }
decl return operator"" name ( long double d ) { body }
decl return operator"" name ( const char* cstr ) { body }
decl return operator"" name ( char_type c ) { body }
decl return operator"" name ( constchar_type * str, size_t sz ) { body }
template <char...>decl return operator"" name ( ){ body }

[edit] Explanation

char_type - one of char, char16_t, char32_t,wchar_t
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

[edit] Examples

#include <iostream>
 
// used as conversion
constexpr long double operator"" _deg ( long double deg )
{
    return deg*3.141592/180;
}
 
// used with custom type
struct mytype
{
    mytype ( unsigned long long m):m(m){}
    unsigned long long m;
};
mytype operator"" _mytype ( unsigned long long n )
{
    return mytype(n);
}
 
// used for side-effects
void operator"" _print ( const char* str )
{
    std::cout << str;
}
 
int main(){
    double x = 90.0_deg;
    std::cout << std::fixed << x << '\n';
    mytype y = 123_mytype;
    std::cout << y.m << '\n';
    0x123ABC_print;
}

Output:

1.570796
123
0x123ABC