Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create templated user-defined literals (literal suffixes) for string literals?

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?

like image 266
HolyBlackCat Avatar asked Dec 01 '16 20:12

HolyBlackCat


People also ask

What are the 6 types of literals?

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.

How do you make a string literal?

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.

What is a literal explain any three literals with an example?

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.


1 Answers

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.

like image 162
T.C. Avatar answered Nov 15 '22 00:11

T.C.