【问题标题】:Why doesn't this template signature work as a string-literal using quotes?为什么此模板签名不能用作使用引号的字符串文字?
【发布时间】:2017-03-23 15:33:12
【问题描述】:

C++11 允许用户定义模板字符串文字运算符,具有以下模板签名(taken from 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) 都没有给出有用的错误信息。 GCC 说:

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 &lt;char...&gt;literal-operators 可以与非数字字符串一起使用?

【问题讨论】:

    标签: c++ c++11 templates user-defined-literals


    【解决方案1】:

    您不能声明接受可变字符包的用户定义字符串文字。这可能会在未来发生变化,但截至目前,仅此而已。

    来自同一个 cppreference:

    对于用户定义的字符串文字,用户定义的文字表达式 被视为函数调用operator "" X (str, len),其中 str 是 没有 ud-suffix 和 len 的文字是它的长度,不包括 终止空字符

    【讨论】:

    • 啊,我明白了——如果其他可能的文字运算符不可用,整数文字和浮点文字被明确地视为函数调用operator "" X&lt;'c1', 'c2', 'c3'..., 'ck'&gt;()。谢谢。
    【解决方案2】:

    Gcc 有 扩展 允许

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

    Demo

    【讨论】:

    • 既然我用 GCC 5 尝试过这个,我想这一定是 GCC 6 中的新功能?
    • 根据that,自gcc 4.9(但使用c++14)。
    • 哦,对了,我用&lt;char...&gt;而不是&lt;typename Char, Char...&gt;
    猜你喜欢
    • 1970-01-01
    • 2010-10-25
    • 2018-09-14
    • 2018-04-08
    • 2016-02-03
    • 2017-02-09
    • 1970-01-01
    • 2023-03-31
    相关资源
    最近更新 更多