为什么此模板签名不能用作使用引号的字符串文字?
Why doesn't this template signature work as a string-literal using quotes?
C++11 允许用户定义模板字符串文字运算符,具有以下模板签名(taken from CppReference;return 类型不需要是 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...>
文字运算符可以与非数字字符串一起使用?
您不能声明接受可变字符包的用户定义字符串文字。这在未来可能会改变,但截至目前,仅此而已。
来自相同的 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
Gcc 有扩展 允许
template <typename Char, Char...Cs>
std::string operator ""_r()
{
// ... construct some sort of string and return it
}
C++11 允许用户定义模板字符串文字运算符,具有以下模板签名(taken from CppReference;return 类型不需要是 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...>
文字运算符可以与非数字字符串一起使用?
您不能声明接受可变字符包的用户定义字符串文字。这在未来可能会改变,但截至目前,仅此而已。
来自相同的 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
Gcc 有扩展 允许
template <typename Char, Char...Cs>
std::string operator ""_r()
{
// ... construct some sort of string and return it
}