重载引用与常量引用 [英] Overloading reference vs const reference

查看:150
本文介绍了重载引用与常量引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

  #include< iostream> 

template< typename T>
void f(T& x)
{
std :: cout< f(T&)<< std :: endl;
}

template< typename T>
void f(const T& x)
{
std :: cout< f(const T&)< std :: endl;
}

int main()
{
int a = 0;
const float b = 1.1;

f(a); // call f(T&)
f(b); // call f(const T&)
}

输出为:

  f(T&)
f(const T&)

我的问题是:编译器如何知道调用哪个函数?如果我从函数定义中删除引用,那么我得到一个模糊调用类型的错误,即错误:redefinition的'f'。对我来说, f(T&)可以同样好地用于这两个调用,为什么 const 明确地调用 f(b)

解决方案

,标准要求编译器选择具有最佳拟合的重载。 (如果没有唯一的最佳重载,或者如果唯一的最佳重载是不可访问的,程序是不成形的。)



在这种情况下,规则由§ 13.3.3.2 [over.ics.rank] / p3:


标准转换序列S1是比标准转换序列S2更好的转换序列if if :

和S2是引用绑定(8.5.3),并且引用引用的类型除了顶级cv限定符之外是相同类型,并且由S2引用初始化的引用所属的类型比c



在标准中:

  int f(const int&); 
int f(int&);
int g(const int&);
int g(int);
int i
int j = f(i); //调用f(int&)
int k = g(i); // ambiguous

在你的情况下, const T& T& 更符合cv限制,所以按照标准, f(T&)拟合比 f(const T&),并通过重载解析选择。


I have the following code:

#include <iostream>

template <typename T>
void f(T& x)        
{
    std::cout << "f(T& )" << std::endl; 
}

template <typename T>
void f(const T& x) 
{ 
    std::cout << "f(const T& )" << std::endl; 
}

int main() 
{
    int a = 0;
    const float b = 1.1;

    f(a); // call f(T&)
    f(b); // call f(const T&)
}

The output is:

f(T& )
f(const T& )

My question is: how does the compiler know which function to call? If I remove the references from the function definitions then I get an "ambiguous call" type of error, i.e. error: redefinition of 'f'. For me it looks like f(T&) can be equally well used for both calls, why is the const version unambiguously called for f(b)?

解决方案

Given two competing overloads, the standard requires the compiler to select the overload that has the "best fit". (If there's no unique best overload, or if the unique best overload is inaccessible, the program is ill-formed.)

In this case, the rules are provided by §13.3.3.2 [over.ics.rank]/p3:

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

  • [...]

  • S1 and S2 are reference bindings (8.5.3), 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.

This is the example given in the standard:

int f(const int &);
int f(int &);
int g(const int &);
int g(int);
int i;
int j = f(i); // calls f(int &)
int k = g(i); // ambiguous

In your case, const T& is more cv-qualified than T&, so by the standard, f(T&) is a better fit than f(const T&) and is selected by overload resolution.

这篇关于重载引用与常量引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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