The general pattern to achieve what you want is to actually execute it in the opposite direction: provide an implicit conversion from T to a pattern and define only the operator for the pattern.
template <typename T> struct test { T m_var; test( T const & t ) : m_var(t) {} // implicit conversion test& operator+=( T const & rhs ) { m_var += rhs.m_var; } friend test operator+( test lhs, test const & rhs ) { // * return lhs += rhs; } }; // * friend only to allow us to define it inside the class declaration
A few details about the idiom: operator+ declared as a friend just to allow us to define a free function inside the curly braces of the class. This has some advantages when it comes to looking for a compiler, as it will only consider this operator if one of the arguments is already test .
Since the constructor is implicit, call test<int> a(0); test<int> b = a + 5; test<int> a(0); test<int> b = a + 5; will be converted to the equivalent of test<int> b( a + test<int>(5) ); And vice versa, if you switch to 5 + a .
operator+ is implemented in terms of operator+= , in a single line, taking the first argument by value. If the operator were more complex, this would have the advantage of providing both operators the same implementation.
source share