c++ - overloading operators of builtin types -
this question has answer here:
while writing code syntactic sugar implementation of power-operator known in python , other languages, operator definition ok, expression operand(s) matching operators signature yields error, operators never defined. there way (compiler option) implement new operators builtin types?
#include <iostream> #include <cmath> template<typename t_float> struct powertmp { t_float value; }; powertmp<double> operator*(double f) { return {f}; }; double operator*(double l, powertmp<double> r) { return std::pow(l, r.value); }; int main() { std::cout << 10.5 *powertmp<double>{2.0} << '\n'; cout << 10.5 ** 2.0 << '\n'; //error };
i using mingw.
edit: clang not support definition of operator.
no, cannot overload operator arguments built-in types. if operator doesn't exist said type.
what can create intermediary type. example:
struct enhanceddouble { double d; }; struct powprecursor { double d; }; powprecursor operator*(enhanceddouble b) { return { b.d }; } enhanceddouble operator*(enhanceddouble lhs, powprecursor rhs) { return { std::pow(lhs.d, rhs.d) }; }
you can sugar little more user defined literal.
enhanceddouble operator""_ed(long double d) { return { (double)d }; }
throw in operator<<
, can this:
std::cout << 4.0_ed ** 4.0_ed; // prints 256
Comments
Post a Comment