Namespaces
Variants
Views
Actions

User-defined literals (since C++11)

From cppreference.com
< cpp‎ | language
Revision as of 01:31, 29 January 2014 by D41D8CD98F (Talk | contribs)

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 ( 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 }

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

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