- integer literal: accepted by a literal operator taking a single unsigned long long or const char* argument.
- floating-point literal: accepted by a literal operator taking a single long double or const char* argument.
- string literal accepted by a literal operator taking a pair of (const char*, size_t) arguments.
- character literal accepted by a literal operator taking a single char argument.
Note that you cannot make a literal operator for a string literal that takes just a const char* argument (and no size). For example:
string operator"" S(const char* p); //warning: this will not work as expected "one two"S; //error: no applicable literal operatorThe problem is the std::string constructor that takes a const char* assumes the input is a C string. C strings are '\0' terminated and thus parsing stops when it reaches the '\0' character. To compensate for this you need to use the constructor that builds the string from a char array (not a C-String). This takes two parameters a pointer to the array and a length:
std::string x("pq\0rs"); // Two characters because input assumed to be C-String std::string x("pq\0rs",5); // 5 Characters as the input is now a char array with 5 characters.Note: C++ std::string is NOT '\0' terminated (as suggested in other posts). Though you can extract a pointer to an internal buffer that contains a C-String with the method c_str().
Reference: UD-literals How do you construct a std::string with an embedded null?
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.