简体   繁体   中英

Conversion from string to const char* + size_t in ""operator

I am reading about the ""operator and found some weird looking code snip, I did not understand.

I did not understand the conervsion from string "110011" to const char *s, size_t l ?

I was expecting something like:

int operator "" _b (const std::string) { .. } or int operator "" _b (const char * s) { .. }

userliteral.cpp

...
int operator "" _b (const char * s, size_t l)
{
     int decimal {0};
     ...//conversion
     return decimal;
} 

main.cpp

int bin2dez01 = "110011"_b;    //<--- string "110011" to const char *s, size_t l ??????
std::cout << bin2dez01 << "\n";

operator "" converts a string literal within the program source into another type, in this case an int based on parsing a string representation of a binary number.

The type of a string literal in C++ is const char * - a constant pointer to an array of char representing the contents of the string. You also get a size_t which tells you how long the string is, because you can't tell that just from the pointer.

(The standard for strings in C and C++ is to put a null byte \\0 to mark the end of the string, but finding that isn't free, and sometimes they get left out by mistake, so it's always easier to pass the pointer and the length around when you can).

The standard string class std::string can be constructed from a string literal, but unlike in languages like C# and Java they are absolutely not the same type. You get the illusion of it a lot because std::string has various conversion operators and overloads to allow you to work more or less seamlessly with string literals in the ways you'd expect to be able to.

So in summary, there's no conversion going on - the string literal really is a const char * , and the size_t tells you how long it is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM