C++11 允许用户定义的模板字符串文字运算符,具有以下模板签名(取自 CppReference;返回类型不需要是double
):
template <char...> double operator "" _x();
但是,这似乎只适用于数字形式,而不是引用形式:
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
GCC (5.1) 和 Clang (3.7) 都没有给出有用的错误信息。海湾合作委员会 说:
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:
// ERROR OUTPUT ENDS HERE
// (nothing is printed here, despite the ':' in the previous line)
Clang 简单地说:
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
那么为什么模板参数推导失败呢?为什么文字运算符模板不匹配?
而且,一般来说,是否可以修复用法以便template <char...>
文字运算符可以与非数字字符串一起使用?