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

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

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

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;
}

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

error: no matching literal operator for call to 'operator""_s.count' with argument of type 'unsigned long long' or 'const char *', and no matching literal operator template
cout << 4_s.count() << endl;

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

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

最佳答案

这就是 float 文字的工作原理!!

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

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

或者,将它们分开(以阻止编译器将其解释为格式错误的小数常量浮点文字):

std::cout << 4_s .count();
//              ^ Space here!

引用:CppReference.com

在上述引用资料的注释部分,

Due to maximal munch, user-defined integer and floating point literals ending in [p, P, (since C++17)] e and E, when followed by the operators + or -, must be separated from the operator with whitespace in the source:

long double operator""_E(long double);
long double operator""_a(long double);
int operator""_p(unsigned long long);

auto x = 1.0_E+2.0;  // error
auto y = 1.0_a+2.0;  // OK
auto z = 1.0_E +2.0; // OK
auto w = 1_p+2;      // error
auto u = 1_p +2;     // OK

所以当点作为小数点使用时,一定要和后面的任何东西分开,否则会被当作 float 的一部分.

我已经从 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-suffix


我原来的解释尝试可以在revision history中找到这篇文章。

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

相关文章:

c++ - 用户定义的文字是在编译时还是运行时解析的?

c++ - 快速可靠的反射球检测方法

c++ - 如何从调用表达式中获取函数的类型?

c++ - std::getline 在 for 循环中不起作用

C++ Lambda : Difference between "mutable" and capture-by-reference

c++ - 未正确推断对全局函数的引用

c++ - 用户自定义文字串 : compile-time length check

c++11 用户定义的物理属性单位文字

c++ - 使用提供额外元素的指针访问数组

c++ - 32 位整数 * 32 位整数 = 64 位整数?