How to customize the literal quantity in C++
What this article shares with you is about how to customize the literal amount in C++. The editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.
Change_speed (Speed s); / / better: the meaning of s is specified / / better: define the meaning of s /... change_speed (2.3); / / error: no unit error: no unit change_speed (23m / 10s); / / meters per second MMI
Line 1 is the function declaration, line 4 is a simple call and there is nothing to say, line 5 is different: it can support operation with units!
Generally speaking, C++ or C languages support writing like 25L, where L is the literal quantity operator. Starting with literal operator 11, the C++ language introduced a technique: by overloading the operator "" (double quotation marks) suffix operator (called the literal operator, literal quantity operator).
Suppose we have the following Distance class:
Struct Distance {explicit Distance (doubleval): meters (val) {} long double meters {0};}
We can define the following literal quantity operators to support m and km units:
Distance operator "" km (long doubleval) {return Distance (val * 1000);} Distance operator "" m (long doubleval) {return Distance (val);} Distance operator "" km (unsigned long long val) {return Distance (val * 1000);} Distance operator "" m (unsigned long long val) {return Distance (val);}
After such a definition, the following code is legal:
Distance d0 {1000}; Distance D1 {1.0km}
After the second form defines D1, the value of d1.meters is 1000. We can also define a Time class in the same way, which supports sec and hour units:
Struct Time {explicit Time (doubleval): seconds (val) {} long double seconds {0}; Time operator "" sec (long doubleval) {return Time (val);} Time operator "" hour (long doubleval) {return Time (val * 3600);} Time operator "" sec (unsigned long long val) {return Time (val);} Time operator "" hour (unsigned long long val) {return Time (val * 3600);}
The next definition of the Speed class that supports the division operator is a regular operation:
Struct Speed {explicit Speed (doubleval): speed (val) {} long double speed;}; Speed operator / (Distance d, Time t) {return Speed (d.meters / t.seconds);}
Once these preparations are complete, you can program like this:
Int main () {Distance d0 {1000}; Distance D1 {1000.0m}; Time T1 {2.0hour}; Speed S1 (D1 / T1); std::cout