2

Here is my code:

#include <iostream>

using namespace std;
class Sales{
  public:
    Sales(int i = 0):i(i){}
    explicit operator int(){ return i; }
  private:
    int i;
};

int main(){
  Sales s(5);
  if(s == 4) cout << "s == 4" << endl;
  else cout << "s != 4" << endl;
  return 0;
}

In c++ primer(5th), it says:

compiler will apply an explicit conversion to an expression used as a condition

But in this case, there is no such conversion. When I delete explicit, the code then works fine.

However, when I change
explicit operator int(){ return i; } to
explicit operator bool(){ return i != 0; },

and change if(s == 4) to if(s) respectively, then the code works fine.

Looks like the convesion rule is a little bit confusing, can anybody explain this in more detail?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Yuan Wen
  • 1,583
  • 3
  • 20
  • 38

1 Answers1

4

Among implicit conversions, since C++11, the explicit user-defined conversion function will be considered for contextual conversions; which happens in the following contexts and when type bool is expected. For int, it's not applied.

In the following five contexts, the type bool is expected and the implicit conversion sequence is built if the declaration bool t(e); is well-formed. that is, the explicit user-defined conversion function such as explicit T::operator bool() const; is considered. Such expression e is said to be contextually convertible to bool.

controlling expression of if, while, for;
the logical operators !, && and ||;
the conditional operator ?:;
static_assert;
noexcept.
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • So, only `operator bool` can be conversed? Others like `int` can not? But I think cpp primer(5th) don't describe this limitation. – Yuan Wen Nov 23 '17 at 01:41
  • 1
    @YuanWen Yes. It only happens when the type `bool` is expected. – songyuanyao Nov 23 '17 at 01:43
  • So, you believe c++ primer(5th) is not clear enough in this topic? – Yuan Wen Nov 23 '17 at 01:45
  • @YuanWen It might want to express that in the contextual conversion (i.e. used as a condition) an explicit conversion to `bool` will be applied, but not precise enough at technical perspective. (But might be enough for initial understanding as a book; and I believe it might be explained more somewhere like appendix. :) ) – songyuanyao Nov 23 '17 at 01:54