Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ make type of variable depend on context?

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 any way to define the variable pi so that operator* and sqrt will operate on floats in Case #1, but will operate on doubles in Case #2?

Perhaps it might be possible with C++14 variable templates?

like image 804
Bernard Avatar asked Mar 06 '17 16:03

Bernard


1 Answers

Sort of. You can certainly define such a pi:

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 have to specify which pi you want:

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

More directly, you could define some pi object that just has 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; }
};

That lets you get the syntax you want, but that's weird, don't do it.

like image 156
Barry Avatar answered Nov 15 '22 12:11

Barry