5

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;
}
Waqar
  • 8,558
  • 4
  • 35
  • 43
User12547645
  • 6,955
  • 3
  • 38
  • 69
  • 1
    It's a *user-defined literal operator*. Waste of time in the context of this being introduced to C++ before modules! – Bathsheba Aug 12 '20 at 11:05
  • "_Can you use it for other things than the creation of custom literals_" - From the link you included: "_[...] Other than the restrictions above, literal operators and literal operator templates are normal functions (and function templates), they can be declared `inline` or `constexpr`, they may have internal or external linkage, they can be called explicitly, their addresses can be taken, etc._" – Ted Lyngmo Aug 12 '20 at 11:17
  • 2
    I have to say that this is a very bad example of a user defined literal. It has you type `30_deg`, but what you get is in *radians*! It makes the code lie. – StoryTeller - Unslander Monica Aug 12 '20 at 13:55
  • I would disagree. `30_deg` still represents 30 degree, but just in radians. So you get exactly what you were promised – User12547645 Aug 12 '20 at 14:09
  • 2
    No, you don't get back degrees. You get back a long double. You wrote "deg", you expect degrees in the double. You feed it into some API, and... crash. The API expected degrees, not radians, and you thought you provided degrees, but it was a lie. I guess people forgot the lessons of the Mars climate orbiter. – StoryTeller - Unslander Monica Aug 12 '20 at 14:17

1 Answers1

2

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.

cigien
  • 57,834
  • 11
  • 73
  • 112