我正在学习用户定义的文字,并与以下测试代码混淆:

std::chrono::seconds operator"" _s(unsigned long long s) {
    return std::chrono::seconds(s);
}

std::string operator"" _str(const char *s, std::size_t len) {
    return std::string(s, len);
}

int main() {
    auto str = "xxxxx"_str;
    std::cout << str.size() << std::endl;    // works

    auto sec = 4_s;
    std::cout << sec.count() << std::endl;   // works

    std::cout << "xxxxx"_str.size() << std::endl;   // works

    std::cout << 4_s.count() << std::endl;   // does **NOT** work!

    return 0;
}

编译器给出以下错误信息:



似乎需要使用 _s.count 作为用户定义的文字。此外,浮点文字的行为类似于整数文字。

为什么用户定义的整数文字和字符串文字具有不同的行为?

最佳答案

这就是浮点文字的工作方式!!

添加一对括号,它应该可以工作:

std::cout << (4_s).count();

或者,将它们分开(以防止编译器将其解释为格式不正确的分数常数浮点文字):
std::cout << 4_s .count();
//              ^ Space here!

引用:CppReference.com

在上述引用的 Notes 部分中,



因此,当涉及点(用作小数点)时,必须将其与后面的任何内容分开,否则将被视为浮点数的部分。

我已经从CppReference测试了上面的示例,并得到了一个非常严重的错误消息:
test.cpp:19:10: error: unable to find numeric literal
operator 'operator""_E+2.0'
                    ^^^^^^
 auto x = 1.0_E+2.0;  // error

知道了如何将_E+2.0视为整个ud后缀?

我的原始解释尝试可以在本文的revision history中找到。

关于c++ - 为什么用户定义的字符串文字和整数文字具有不同的行为?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48968598/

10-11 23:08
查看更多