Kyle Strand Kyle Strand - 2 months ago 10
C++ Question

Why doesn't this template signature work as a string-literal using quotes?

C++11 permits user-defined template string-literal operators, with the following template signature (taken from CppReference; the return type does not need to be


template <char...> double operator "" _x();

However, it appears that this only works in the numeric form, not the quoted form:

template <char... chs>
std::string operator ""_r()
// ... construct some sort of string and return it

// ...

auto my_str = "abc"_r; // ERROR (compiler messages copied below)
auto my_num = 123_r; // NO ERROR

Neither GCC (5.1) nor Clang (3.7) give a useful error message. GCC says:

error: no matching function for call to ‘operator""_r()’
// printed source elided
note: candidate: template<char ...chs> std::__cxx11::string operator""_r()
// printed source elided
note: template argument deduction/substitution failed:
// (nothing is printed here, despite the ':' in the previous line)

Clang simply says:

error: no matching literal operator for call to 'operator "" _r' with arguments of types 'const char *' and 'unsigned long', and no matching literal operator template

So why does template argument deduction fail? Why does the literal operator template not match?

And, in general, is it possible to fix the usage so that
template <char...>
literal-operators can be used with non-numeric strings?


You cannot declare user-defined string literals that accepts a variadic char pack. This may change in the future, but as of now, that's all there is to it.

From the same cppreference:

For user-defined string literals, the user-defined literal expression is treated as a function call operator "" X (str, len), where str is the literal without ud-suffix and len is its length excluding the terminating null character