Why do user-defined string literals and integer literals have different behavior?

前端 未结 1 1686
野趣味
野趣味 2020-12-14 08:18

I\'m learning about user-defined literals, and confused with the following test code:

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


        
相关标签:
1条回答
  • 2020-12-14 08:55

    That's how floating point literals work!!

    Add a pair of parentheses and it should work:

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

    Or alternatively, separate them (to stop the compiler from interpreting it as an ill-formed fractional constant floating point literal):

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

    Reference: CppReference.com

    In the Notes section of the reference above,

    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
    

    So when it comes to dot, which is used as decimal point, it must be separated from anything behind, or it'll be treated as part of the floating point number.

    I have tested the example above from CppReference and got a very silimar error message:

    test.cpp:19:10: error: unable to find numeric literal
    operator 'operator""_E+2.0'
                        ^^^^^^
     auto x = 1.0_E+2.0;  // error
    

    Got the point how _E+2.0 is considered as a whole ud-suffix?


    My original explanation attempt can be found in the revision history of this post.

    0 讨论(0)
提交回复
热议问题