c++ - Implicitly convert object to floating point type when arithmetics are performed with it -
assume have global object pi
, want implicitly convert either float
or double
depending on context. following 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 why not work compiler not know whether should implicitly convert pi
float
or double
. however, want convert type of other operand in binary arithmetic operator. there elegant way achieve in c++11 or later or should overload arithmetic operators? 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; } //... };
or can come more elegant solution implicitly converting global object appropriate type context?
your first try close. let's add templated *
operator outside class:
template<typename t> t operator*(const pi& pi, t&& other) { return static_cast<t>(pi) * std::forward<t>(other); }
and works. live demo
full code
#include <cmath> #include <iostream> #include <iomanip> 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; template<typename t> t operator*(const pi& pi, t&& other) { return static_cast<t>(pi) * std::forward<t>(other); } int main() { std::cout << std::setprecision(50) << pi * 1.0f << std::endl; std::cout << std::setprecision(50) << pi * 1.0 << std::endl; }
output:
3.1415927410125732421875
3.141592653589793115997963468544185161590576171875
if want strict substitutes t
std::enable_if
, std::is_floating_point
within type_traits
Comments
Post a Comment