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

前端 未结 5 1719
遥遥无期
遥遥无期 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:32

    Yes, defining your own user defined literal in the global namespace results in an ill-formed program.

    I haven't run into this myself, because I try to follow the rule:

    Don't put anything (besides main, namespaces, and extern "C" stuff for ABI stability) in the global namespace.

    namespace Mine {
      struct meter { double value; };
      inline namespace literals {
        meter operator ""_m( double v ) { return {v}; }
      }
    }
    
    int main() {
      using namespace Mine::literals;
      std::cout << 15_m.value << "\n";
    }
    

    This also means you cannot use _CAPS as your literal name, even in a namespace.

    Inline namespaces called literals is a great way to package up your user defined literal operators. They can be imported where you want to use it without having to name exactly which literals you want, or if you import the entire namespace you also get the literals.

    This follows how the std library handles literals as well, so should be familiar to users of your code.

提交回复
热议问题