C ++重载解析,转换运算符和const [英] C++ overload resolution, conversion operators and const

查看:123
本文介绍了C ++重载解析,转换运算符和const的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这种情况下

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

情况非常清楚-f(int *)被调用似乎是正确的.

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);

运算符char *()被调用.我不知道为什么这样的决策路径会比使用运算符bool()更好.有什么想法吗?

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

(*)如果将const添加到第二个运算符,则代码将按预期工作.

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

推荐答案

由于使用转换运算符进行用户定义的转换,因此将返回类型转换为目标类型(即,将char*转换为bool)视为之后对象参数的转换,即对象参数a到隐式对象参数的转换. [over.match.best]/1:

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

鉴于这些定义,可行的功能F1被定义为 如果对于所有参数,则其功能优于另一个可行的功能F2 i ICS i ( F1 )转换顺序不比 ICS i ( F2 )差,然后

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

  • 对于某些自变量 j ICS j ( F1 )是比 ICS j ( F2 ),如果不是,则

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

上下文是通过用户定义的转换初始化的(请参见8.5、13.3.1.5和13.3.1.6).F1的返回类型到目标类型(即 实体被初始化)是比标准转换顺序更好的转换顺序 F2返回目标类型的返回类型.

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 (i.e., 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.

因此,由于作为引用的隐式对象参数不是operator char*const-引用,因此根据第一个要点,它是一个更好的匹配.

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.

这篇关于C ++重载解析,转换运算符和const的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆