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;
}
%= Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand. C %= A is equivalent to C = C % A.
The logical AND operator ( && ) returns true if both operands are true and returns false otherwise. The operands are implicitly converted to type bool before evaluation, and the result is of type bool .
%d is a format specifier, used in C Language. Now a format specifier is indicated by a % (percentage symbol) before the letter describing it. In simple words, a format specifier tells us the type of data to store and print. Now, %d represents the signed decimal integer.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With