Is every “normal” use of user-defined literals undefined behavior?

前端 未结 5 1770
遥遥无期
遥遥无期 2021-01-18 03:07

User defined literals must start with an underscore.

This is a more or less universally well-known rule that you can find on every layman-worded site talkin

5条回答
  •  难免孤独
    2021-01-18 03:25

    Is every “normal” use of user-defined literals undefined behavior?

    Clearly not.

    The following is the idiomatic (and thus definitely “normal”) use of UDLs, and it’s well-defined according to the rule you’ve just listed:

    namespace si {
        struct metre { … };
    
        constexpr metre operator ""_m(long double value) { return metre{value}; }
    }
    

    You’ve listed problematic cases and I agree with your assessment about their validity but they’re easily avoided in idiomatic C++ code so I don’t entirely see the problem with the current wording, even if it was potentially accidental.

    According to the example in [over.literal]/8, we can even use capital letters after the underscore:

    float operator ""E(const char*);    // error: reserved literal suffix (20.5.4.3.5, 5.13.8)
    double operator""_Bq(long double);  // OK: does not use the reserved identifier _Bq (5.10)
    double operator"" _Bq(long double); // uses the reserved identifier _Bq (5.10)
    

    The only problematic thing thus seems to be the fact that the standard makes the whitespace between "" and the UDL name significant.

提交回复
热议问题