I was suprised when I discovered that it's possible to make user-defined literals templated:
template <char ...C> std::string operator ""_s()
{
char arr[]{C...};
return arr;
}
// ...
std::cout << 123_s;
But above declaration does not work with string literals:
"123"_s
gives me following error:
prog.cpp: In function 'int main()':
prog.cpp:12:15: error: no matching function for call to 'operator""_s()'
std::cout << "123"_s;prog.cpp:4:34: note: candidate: template std::string operator""_s()
template std::string operator ""_s()prog.cpp:4:34: note: template argument deduction/substitution failed:
(Ideone)
Is there is a way to use templated user-defined literals with string literals as well?
Primitive data types include int, byte, short, float, boolean, double, and char, whereas non-primitive data types include arrays, string, and classes. The primitive literals in java int, byte, short, float, boolean, double, and char represent certain signed integer values.
This means that a string literal is written as: a quote, followed by zero, one, or more non-quote characters, followed by a quote. In practice this is often complicated by escaping, other delimiters, and excluding newlines.
Literals are the constant values assigned to the constant variables. We can say that the literals represent the fixed values that cannot be modified. It also contains memory but does not have references as variables. For example, const int =10; is a constant integer expression in which 10 is an integer literal.
Clang and GCC support an extension that allows you to do
template<class CharT, CharT... Cs>
std::string operator ""_s() { return {Cs...}; }
But there is nothing in standard C++; proposals to standardize this have been made several times and rejected each time, most recently less than a month ago, mostly because a template parameter pack is a really inefficient way to represent strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With