Note that there are some explanatory texts on larger screens.

plurals
  1. POc++ Overload operator bool() gives an ambiguous overload error with operator+
    primarykey
    data
    text
    <p>I'm compiling some c++ code of a class MegaInt which is a positive decimal type class that allows arithmetic operations on huge numbers.</p> <p>I want to overload operator bool to allow code like this:</p> <pre><code>MegaInt m(45646578676547676); if(m) cout &lt;&lt; "YaY!" &lt;&lt; endl; </code></pre> <p>This is what I did:</p> <p>header:</p> <pre><code>class MegaInt { public: ... operator bool() const; }; const MegaInt operator+(const MegaInt &amp; left, const MegaInt &amp; right); const MegaInt operator*(const MegaInt &amp; left, const MegaInt &amp; right); </code></pre> <p>implementation:</p> <pre><code>MegaInt::operator bool() const { return *this != 0; } const MegaInt operator+(const MegaInt &amp; left, const MegaInt &amp; right) { MegaInt ret = left; ret += right; return ret; } </code></pre> <p>Now, the problem is if I do:</p> <pre><code>MegaInt(3424324234234342) + 5; </code></pre> <p>It gives me this error:</p> <blockquote> <p>ambiguous overload for 'operator+' in 'operator+(const MegaInt&amp;, const MegaInt&amp;) note: candidates are: operator+(int, int) | note: const MegaInt operator+(const MegaInt&amp;, const MegaInt&amp;)|</p> </blockquote> <p>I don't know why. How is the overloaded bool() causing operator+ to become ambiguous?¸</p> <p>Thank You.</p> <hr> <p>Well, everyone gave me great answers, unfortunately, none of them seem to solve my problem entirely.</p> <p><strong>Both void* or the Safe Bool Idiom works.</strong> Except for one tiny problem, I hope has a workaround:</p> <p>When comparing with 0 like:</p> <pre><code>if (aMegaInt == 0) </code></pre> <p>The compiler gives an ambiguous overload error again. I understand why: it doesn't know if we're comparing to false or to MegaInt of value 0. None the less, in that case, I'd want it to cast to MegaInt(0). Is there a way to force this?</p> <p>Thank You Again.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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