Implicit conversion to boolean and comparison with boolean literals

I answered this question about the topic of custom transformations booland how to disable other transformations:

struct foo
{
    operator bool() const //Explicit overload for bool
    {
       return true; 
    }

  template<typename T>
  operator T() const = delete; //Everithing which is not a bool (Everithing which  
                               //does not fit in the explicit overload) would  
                               //resolve to this operator and will fail.
};


int main()
{
    foo f;

    bool b = f; //OK
    int i = f;  //ERROR
    char c = f; //ERROR
    etc...
}

Later, the OP asked me why conditions like this if( f == true )did not work (where f- foo. I tried this myself, and it surprises me because this comparison with boolean literals leads to conversion to int(Which is disabled) instead bool:

int main()
{
    foo f;

    if( f ); //OK, converts to bool
    if( f == true ); //ERROR: Conversion to int, which has been disabled
}  

prog.cpp: 20: 12: error: using the remote function 'foo :: operator T () const [with T = int] if (f == true);
.................................................. .................................................. .......................................... ^

: ( C #define true 1 #define false 0), , int bool?

GCC4.8.1 ++ 11 (-std=C++11).

ideone.

+4
3

foo - , , , . [over.built]/12

L R

LR operator*(L, R);
LR operator/(L, R);
LR operator+(L, R);
LR operator-(L, R);
bool operator<(L, R);
bool operator>(L, R);
bool operator<=(L, R);
bool operator>=(L, R);
bool operator==(L, R);
bool operator!=(L, R);

LR L R.

" ": bool.

A bool int, . [conv.prom]/6 ( )

bool prvalue int, false , true .


,

common_type<L,int> operator==(L, int);

L . ,

common_type<int      , int> operator==(int      , int);
common_type<long     , int> operator==(long     , int);
common_type<long long, int> operator==(long long, int);

foo . , , foo . CWG 954.

, g++ 4.8.1 clang++ 3.5 . ( , clang , . , g++ 4.8.1.)


common_type<bool, int> operator==(bool, int);

as bool . foo bool

foo x;
x == true
+2

bool #defined ++. , int int.

0

Let's do a quick test here:

template <typename T>
struct OutputType;

int main()
{
    OutputType<decltype(true)> a;
}

Atleast ideone deduces here that it truehas type bool: http://ideone.com/Gm653T

But:

The bool type can be converted to int with a false value of 0, and true - 1.

Source: cppreference

And I assume that this is precisely the kind of progress that is taking place here.

0
source

Source: https://habr.com/ru/post/1523694/


All Articles