C ++ overload resolution, conversion operators and const

In this case

void f(int *);
void f(const int *);
...
int i;
f(&i);

the situation is pretty clear - the f (int *) call seems correct.

However, if I have this (this was done by mistake (*)):

class aa
{
public:
    operator bool() const;
    operator char *();
};

void func(bool);

aa a;
func(a);
Operator

char * () is called. I can’t understand why such a solution would be better than going to the bool () operator. Any ideas?

(*) If a constant is added to the second statement, the code works as expected, of course.

+4
source share
3 answers

(.. char* bool) , a . [Over.match.best]/1:

, F1 , F2, i, ICS i (F1) , ICS i (F2),

  • j, ICS j (F1) , ICS j (F2), , ,

  • (. 8.5, 13.3.1.5 13.3.1.6) ,       F1 (      ) ,     F2 .

, , const -reference operator char*, .

+3

a - aa, () , const ( ), .

+1

Your "aa" object is not constant, so C ++ prefers non-constant conversion.

If you create an "aa" const, then the conversion operator const bool () will be used.

0
source

All Articles