Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The reason it does not <em>just work</em> is that implicit type conversions (that is, via constructors) do not apply during template argument deduction. But it works if you make the outside operator a friend since then the type T is know, allowing the compiler to investigate what can be casted to make the arguments match.</p> <p>I made an example based on yours (but removed C++11 stuff), inspired by Item 46 (a rational number class) in Scott Meyers Effective C++ (ed 3). Your question is almost an exact match to that item. Scott also notes that ... "this use of friend is not related to the access of non-public parts of the class."</p> <p>This will also allow work with mixes of foo&lt; T >, foo&lt; U > etc as long as T and U can be added etc.</p> <p>Also look at this post: <a href="https://stackoverflow.com/questions/2613645/c-addition-overload-ambiguity">C++ addition overload ambiguity</a></p> <pre><code>#include &lt;iostream&gt; using namespace std; template&lt; class T &gt; class foo { private: T _value; public: foo() : _value() {} template &lt;class U&gt; foo(const foo&lt;U&gt;&amp; that) : _value(that.getval()) {} // I'm sure this it can be done without this being public also; T getval() const { return _value ; }; foo(const T&amp; that) : _value(that) {} friend const foo operator +(foo &amp;lhs,const foo &amp;rhs) { foo result(lhs._value+rhs._value); return result; }; friend const foo operator +(foo &amp;lhs,const T &amp;rhsval) { foo result(lhs._value+rhsval); return result; }; friend const foo operator +(const T &amp;lhsval,foo &amp;rhs) { foo result(lhsval+rhs._value); return result; }; friend foo&amp; operator +=(foo &amp;lhs,const foo &amp;rhs) { lhs._value+=rhs._value; return lhs; }; friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const foo&amp; me){ return out &lt;&lt;me._value; } }; int main(){ foo&lt; int &gt; f, g; foo&lt; double &gt; dd; cout &lt;&lt;f&lt;&lt;endl; f = f + g; cout &lt;&lt;f&lt;&lt;endl; f += 3 ; cout &lt;&lt;f&lt;&lt;endl; f = f + 5; cout &lt;&lt;f&lt;&lt;endl; f = 7 + f; cout &lt;&lt;f&lt;&lt;endl; dd=dd+f; cout &lt;&lt;dd&lt;&lt;endl; dd=f+dd; cout &lt;&lt;dd&lt;&lt;endl; dd=dd+7.3; cout &lt;&lt;dd&lt;&lt;endl; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload