6
votes

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?

1
what do you want to achieve? Note you cannot do << foo_s; either, no need for quotes to make it fail.Jean-François Fabre♦
@Jean-FrançoisFabre I know. Of course that's not a real use case. I want to be able to generate a unique type based on a string literal and that could be one of the possible ways.HolyBlackCat

1 Answers

2
votes

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.