HolyBlackCat HolyBlackCat - 7 days ago 5
C++ Question

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?

Answer

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.