Overload resolution C++ for const member functions

自古美人都是妖i 提交于 2019-11-30 21:02:53

In N3242 (the standard draft I have on hand), 13.3.1 paragraph 4 says

the type of the implicit object parameter is "lvalue reference to cv X” for [non-static member] functions declared without a ref-qualifier or with the & ref-qualifier

this means that type of the implicit object argument, which occurs first, is an "lvalue reference to cv X", where X is the class, and cv is the cv-qualification of the member variable (i.e. const or non-const). Then, overload resolution continues as normal.

To review the overload resolution process, first, both are listed as "candidate" functions as they are in the correct scope and have the correct name.

In the const case, only the const member function gets to the next step (called "viability"), so it's automatically the best choice. The non-const member function is not viable because you can't convert a const reference into a non-const reference.

In the non-const case, both the const and non-const versions are viable, but the non-const one is "better" because of the fifth rule of 13.3.3.2 paragraph 3, quoted below.

Standard conversion sequence S1 is a better conversion sequence than standard conversion sequence S2 if ...

S1 and S2 are reference bindings, and the types to which the references refer are the same type except for top-level cv-qualifiers, and the type to which the reference initialized by S2 refers is more cv-qualified than the type to which the reference initialized by S1 refers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!