Note that there are some explanatory texts on larger screens.

plurals
  1. POC++ Operator Overloading : Multiplication of User Defined Type by floating point values
    text
    copied!<p>I am trying to implement multiplication operators (<code>operator*</code>) for 4 situations.</p> <p>Imagine I have a <code>class rain</code>.</p> <pre><code>namespace manchester { namespace manchester_private_dont_use_this { template&lt;typename T&gt; class rain { public: rain(T initial_rain) : m_rain(initial_rain) { } private: T m_quantity_of_rain; }; } } //namespace manchester </code></pre> <p>Assume this class is declared inside a private namespace. <code>typedef rain&lt;float&gt; rainf;</code> and <code>typedef rain&lt;double&gt; raind</code> expose the functionality of this class inside a non-private namespace. By private namespace I mean another nested namespace which is called something like <code>namespace rainprivate_do_not_use_me</code>. (In the example I actually added two namespaces to explain what I'm talking about, but that's not really important.) That's the best I could come up with to prevent the end user (me) from trying to create a <code>rain&lt;int&gt;</code> which doesn't make much sense, since rain is measured in litres., and therefore we can have non-integer quantities.</p> <p>Anyway, I was to implement <code>operator*</code> like I said, for the case of multiplying a quantity of rain by both a <code>float</code> and a <code>double</code>. Am I correct in assuming that since these types can be implicitly converted, I only need to implement an operator where the rhs variable is a <code>double</code> and where the lhs variable is a <code>double</code>. (By double I actually mean the type, T.)</p> <p>Again, I am guessing here - see my previous question about unary operators, but I guess something like this: (Again I couldn't find any info on SO to answer my question.)</p> <pre><code>// friend function: inline rain&lt;T&gt; operator*(const rain&lt;T&gt;&amp; _rain, const T _t) { return rain&lt;T&gt;(_rain.m_quantity_of_rain * _t); } inline rain&lt;T&gt; operator*(const T _t, const rain&lt;T&gt;&amp; _rain) { return rain&lt;T&gt;(_rain.m_quantity_of_rain * _t); } </code></pre> <p>Again, I was unsure so thought its probably better to ask than learn it wrong. The 4 situations I was thinking of was the two above, and then the two hidden cases for when <code>float</code> may be converted to double<code>in the case when</code>T<code>is type</code>double`, and vice versa.</p>
 

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