简体   繁体   中英

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 - f(int *) gets called which seems right.

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

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

void func(bool);

aa a;
func(a);

operator char *() gets called. I cannot figure out why would such decision path be better than going to operator bool(). Any ideas?

(*) If const is added to the second operator, the code works as expected, of course.

Because for user-defined conversions with a conversion operator the conversion of the returned type to the destination type (ie char* to bool ) is considered after the object argument conversion, ie the conversion of the object argument a to the implicit object parameter. [over.match.best]/1:

Given these definitions, a viable function F1 is defined to be a better function than another viable function F2 if for all arguments i , ICS i ( F1 ) is not a worse conversion sequence than ICS i ( F2 ) , and then

  • for some argument j , ICS j ( F1 ) is a better conversion sequence than ICS j ( F2 ) , or, if not that ,

  • the context is an initialization by user-defined conversion (see 8.5, 13.3.1.5, and 13.3.1.6) and the standard conversion sequence from the return type of F1 to the destination type (ie, the type of the entity being initialized) is a better conversion sequence than the standard conversion sequence from the return type of F2 to the destination type .

So because the implicit object parameter, which is a reference, is not a const -reference for operator char* , it is a better match according to the first bullet point.

aaa的非const实例,因此非const转换运算符是比const(更好)(需要添加常量)更好(精确)匹配,即使返回类型也不匹配。

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM