Simple implementation of operators between different c++ classes -
is there simple/smart way implement missing operator: ‘operator+’ (operand types ‘myclassref<int>’ , ‘myclass<int>’)
these 2 classes? know define function takes these 2 types parameters. since implementing several function should take both myclass
, myclassref
types parameters in simple manner.
i have been looking having myclassref
inner class of myclass
, using implicit conversion, method (to best of knowledge) required function using both types parameters member functions.
#include <iostream> using namespace std; template <class t> struct myclass; template <class t> struct myclassref { t* i; myclassref(myclass<t>* a) { = &a->i; } operator myclass<t>() { return myclass<t>(*i); } t& get() { return *i; } }; template <class t> struct myclass { t i; myclass() = default; myclass(const myclass&) = default; myclass(t _i) : i(_i) {} myclassref<t> ref() { return myclassref<t>(this); } t& get() { return i; } t get() const { return i; } }; template <class t> myclass<t>& operator+=(myclass<t>& lhs, const myclass<t>& rhs) { lhs.get() += rhs.get(); return lhs; } template <class t> myclass<t> operator+(const myclass<t>& lhs, const myclass<t>& rhs) { myclass<t> res(lhs); res += rhs; return res; } int main() { myclass<int> a(5); myclass<int> b(2); auto c = + b; std::cout << c.i << std::endl; auto d = c.ref(); = d + b; return 0; }
there's no need use inner classes. instead, should build 2 global operators, exist outside both classes this:
t operator+(const myclassref<int>&, const myclass<int>&)
and overload
t operator+(const myclass<int>&, const myclassref<int>&)
where t
return type decide upon. if either of these functions require private data within classes, make functions friend
of 2 classes putting these declarations in class declarations:
friend t operator+(const myclassref<int>&, const myclass<int>&); friend t operator+(const myclass<int>&, const myclassref<int>&);
moving on, might want make these functions templates on type of myclassref
, although more modern compilers support making template functions friends.
Comments
Post a Comment