为什么具有“相同签名"的模板和非模板函数的重载?调用非模板函数? [英] Why does overload of template and non-template function with the "same signature" call the non-template function?

查看:31
本文介绍了为什么具有“相同签名"的模板和非模板函数的重载?调用非模板函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

template<
    class T = const int &
> void f(T) {}

void f(const int &) {}

int main() {
   f(0);
}

为什么它调用第二个而不是第一个?我会认为它们是相同的,但它们显然不是,因为我没有收到重新定义错误.

Why does it call the second one instead of first? I would think of them as being the same but they're clearly not as I do not get a redefinition error.

推荐答案

因为第二个重载不是模板.

Because the second overload is not a template.

当模板函数和非模板函数都可用于解析函数调用时,选择非模板函数.

When a template function and a non-template function are both viable for resolving a function call, the non-template function is selected.

来自 C++ 11 标准的第 13.3.3/1 段:

From Paragraph 13.3.3/1 of the C++ 11 Standard:

[...] 鉴于这些定义,如果对于所有参数 i,ICSi(F1) 不是更差的转换,则可行函数 F1 被定义为比另一个可行函数 F2 更好的函数序列比ICSi(F2),然后[...] F1是一个非模板函数,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 [...] F1 is a non-template function and F2 is a function template specialization [...]

这篇关于为什么具有“相同签名"的模板和非模板函数的重载?调用非模板函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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