为什么具有“相同签名"的模板和非模板函数的重载?调用非模板函数?

Why does overload of template and non-template function with the quot;same signaturequot; call the non-template function?(为什么具有“相同签名的模板和非模板函数的重载?调用非模板函数?)
本文介绍了为什么具有“相同签名"的模板和非模板函数的重载?调用非模板函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有这个代码:

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 [...]

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)
STL BigInt class implementation(STL BigInt 类实现)
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)