为什么const临时函数选择调用非const成员函数而不是const成员函数?
How come a const temporary chooses to call a non-const member function over a const one?
示例代码取自:http://en.cppreference.com/w/cpp/types/add_cv(我修改了一点)
struct foo
{
void m() { std::cout << "Non-cvn"; }
void m() const { std::cout << "Constn"; }
};
template<class T>
void call_m()
{
T().m();
}
int main()
{
call_m<foo>();
call_m<const foo>(); //here
}
输出为:
Non-cv
Non-cv
在第二次调用中,T
是const限定的,所以T()
应该调用const版本,对吗?还是我错过了一些特殊的规则?
标准中的相关引语为5.2.3 [exp .type.conv]/2
表达式T(),其中T是非数组完整对象类型或(可能是cv限定的)void类型的简单类型说明符或类型名称说明符,创建指定类型的右值,该右值是value- initialized (8.5;对于void()情况,没有进行初始化。[注:如果T是cv限定的非类类型,则在确定结果右值的类型时忽略cv限定符(3.10)。]-end note]
标准中的措辞明确地提到(以非规范的形式)对于非类类型,const-volatile限定被删除,但在您的示例中,类型是类,因此注释不适用。
相关文章:
- 为什么这个函数将"const char*"转换为"void* const"而不是"const void*"
- 从函数返回const char*数组
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 在 const 函数中通过引用和指针返回之间的区别
- 使用 std::string () const 函数启动线程或未来
- 在运算符重载定义中使用成员函数(const错误)
- 使用共享指针的函数调用,其对象应为 const
- 将函数参数"const char*"转换为"std::string_view"是
- 为什么返回类型的'const'限定符对标有 __forceinline/内联的函数没有影响?
- 使用按引用调用时,不能在没有对象的情况下调用成员函数 const
- 在呼叫运算符函数const中调用运算符时错误
- 我需要用c ++ 98重写c ++ 11代码,c ++ 11正在使用lambda函数[&](const Output & o
- 函数 const 本地对象在C++会发生什么
- int const函数(参数)、int函数(const参数)和int函数(parameters)const之间的区别是什
- const_cast为函数const设置规则并破坏规则
- 构造函数"const variables"设置的用于表示C++数组的边界?
- 将char**传递给C++中的函数(const char**)
- 复制构造函数const char*和Shared_ptr
- 使函数"const"的意图是什么
- c++嵌套映射不匹配成员函数const成员