5

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?

0

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

3 Comments

@T.C. Something like that?
You may make it simplier - default implementation should define double value instead of int. template <class T> constexpr double pi = 3.0;
@Orient Great idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.