C ++ makes a variable type context sensitive?

I have the following code:

// Case #1 float f = 1.0f; float f2 = sqrt(f * pi); // Case #2 double d = 1.0; double d2 = sqrt(d * pi); 

Is there a way to define the variable pi so that operator* and sqrt work on float in case # 1, but will work on double in case # 2?

Perhaps this is possible with C ++ 14 variable templates?

+5
source share
1 answer

Grade. You can define a pi like this:

 template <class T> constexpr double pi = 3.14159...; template <> constexpr long double pi<long double> = 3.14159...L; template <> constexpr float pi<float> = 3.14159...F; 

But you must specify which pi you want:

 float f2 = sqrt(f * pi<float>); double d2 = sqrt(d * pi<double>); 

More specifically, you can define some pi object that simply overloaded operator* depending on the type:

 struct Pi { template <class T> decltype(pi<T>) operator*(T val) { return val * pi<T>; } template <class T> friend decltype(pi<T>) operator*(T val, Pi) { return pi<T> * val; } }; 

This allows you to get the syntax you want, but it's weird, don't do this.

+11
source

Source: https://habr.com/ru/post/1265098/


All Articles