Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User defined const char* literal example from cppreference

On cppreference there is this example (http://en.cppreference.com/w/cpp/language/user_literal):

void operator"" _print ( const char* str )
{
    std::cout << str;
}


int main(){
    0x123ABC_print;
}

Output: 0x123ABC

And I fail to understand what exactly this is doing. First I thought that 0x123ABC would just be seen as a string, but 0x123ABCHello_print doesn't compile. Then I thought that the operator<< is overloaded so that it always prints it in hexadecimal form, but 123_print prints 123. Also it's case-sensitive: 0x123abC_print prints 0x123abC.

Can someone explain this to me? On one hand it only takes integers as argument but on the other it treats them like string literals.

like image 646
Michael Mahn Avatar asked Dec 13 '25 18:12

Michael Mahn


2 Answers

http://en.cppreference.com/w/cpp/language/user_literal

void operator"" _print(const char* str) shows that your literal is taken as const char* and then printed out, it's why it's case-sensitive.

0x123ABCHello_print doesn't work because 0x123ABCHello is not a number, for user-defined string literals you'd need "0x123ABCHello"_print

like image 121
Andriy Tylychko Avatar answered Dec 16 '25 08:12

Andriy Tylychko


In the example code you see:

12_w; // calls operator "" _w("12")

Which means that an integer literal is converted to a const char[]. This is then accepted by your user-defined literal. Since it's a const char* ,operator<< will just print until it hits \0, no special handling as you'd have normally when printing out an integer literal such as std::cout << 0xBADFOOD;.

like image 30
Hatted Rooster Avatar answered Dec 16 '25 10:12

Hatted Rooster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!