Suppose we have a global object pi, and we want to implicitly convert it to floator doubledepending on the context. The following does not work:
#include <cmath>
class Pi {
public:
Pi() {}
operator float() const {
return std::atan(1.0f)*4.0f;
}
operator double() const {
return std::atan(1.0)*4.0;
}
};
const Pi pi;
#include <iostream>
#include <iomanip>
int main() {
std::cout << std::setprecision(50) << pi * 1.0f << std::endl;
std::cout << std::setprecision(50) << pi * 1.0 << std::endl;
}
The reason it does not work is because the compiler does not know if it should implicitly convert pito floator double. However, let's say we always want it to convert to the type of another operand in a binary arithmetic operator. Is there some elegant way to achieve this in C ++ 11 or later, or do I need to overload all arithmetic operators? Something like that:
class Pi {
public:
Pi() {}
float operator*(float x) const {
return (std::atan(1.0f)*4.0f) * x;
}
double operator*(double x) const {
return (std::atan(1.0)*4.0) * x;
}
};
?