3

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.

Praetorian
  • 106,671
  • 19
  • 240
  • 328
Michael Mahn
  • 737
  • 4
  • 11

2 Answers2

3

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

Andriy Tylychko
  • 15,967
  • 6
  • 64
  • 112
2

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;.

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122