c++operator-overloadinguser-defined-literals

What does the operator"" do in C++?


How do you call this operator?

Can you use it for things other than the creation of custom literals?

Example usage: (see cppreference)

constexpr long double operator"" _deg ( long double deg )
{
    return deg * 3.14159265358979323846264L / 180;
}

Solution

  • The primary usage of this operator"" is the creation of user-defined-literals. From the reference:

    Allows integer, floating-point, character, and string literals to produce objects of user-defined type by defining a user-defined suffix.


    You can call this operator as you would any other overloaded operator:

    std::cout << 42.5_deg;                // with convenient operator syntax
    std::cout << operator"" _deg(42.5);   // with an explicit call
    

    Not entirely unrelated: as pointed out in the comments to your question, this example is badly named. It takes in degrees and returns radians, so it should probably be named operator"" _rads. The purpose of UDLs is to have convenient, easy to read syntax, and a function that lies about what it does actively undermines that.


    You can use this operator to do pretty much any computation you want (with constraints on the type, and number of the arguments passed in, similar to other operators), for example:

    constexpr long double operator"" _plus_one ( long double n )
    {
        return n + 1;
    }
    

    Though the usage of this operator would still be the same as above.

    Here's a demo.