1

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...>文字运算符可以与非数字字符串一起使用?

4

2 回答 2

2

您不能声明接受可变字符包的用户定义字符串文字。这在未来可能会改变,但到目前为止,这就是它的全部。

来自同一个 cppreference:

对于用户定义的字符串字面量,用户定义的字面量表达式被视为函数调用operator "" X (str, len),其中 str 是不带ud 后缀的字面量,len 是不包括终止空字符的长度

于 2016-11-09T18:21:21.857 回答
1

Gcc 有扩展允许

template <typename Char, Char...Cs>
std::string operator ""_r()
{
    // ... construct some sort of string and return it
}

演示

于 2016-11-09T19:08:31.450 回答