User Defined Definitions

I looked at the cppreference page for custom literals and I think I understand everything except a few examples

template <char...> double operator "" _π(); // OK

How does this operator work? What can you call it?

double operator"" _Z(long double); // error: all names that begin with underscore
                                   // followed by uppercase letter are reserved
double operator""_Z(long double); // OK: even though _Z is reserved ""_Z is allowed

What is the difference between the two above functions? What is the difference in calling the first function, and not the second, if the first was not an error?

Thank!

+4
source share
2 answers
template <char...> double operator "" _π(); // OK

How does this operator work? What can you call it?

1.234_π operator "" _π<'1', '.', '2', '3', '4'>(). , (1.2 vs 1.20, ), - , 1.2 long double.

double operator"" _Z(long double); // error: all names that begin with underscore
                                   // followed by uppercase letter are reserved
double operator""_Z(long double); // OK: even though _Z is reserved ""_Z is allowed

?

++ , . "" _Z - , "" _Z. ""_Z - .

: #define S " world!", "Hello" S, - , S , .

, , "" _Z ""_Z , "" _Z , _Z . , _Z .

+6

, .

, _Z . , :

double operator""/*space*/_Z(long double); 

double operator""_Z(long double); 

, (, , ).

, ?

#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;
}

, , , .

EDIT:

, . , :

// used as conversion
constexpr long double operator"" _deg ( long double deg )
{
    return deg*3.141592/180;
}

, :

long double d = 45_deg;

template <char...> double operator "" _π(); , .

+1

Source: https://habr.com/ru/post/1667457/


All Articles