我有这个代码:
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 [...]
这篇关于为什么具有“相同签名"的模板和非模板函数的重载?调用非模板函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
为什么两个函数的地址相同?Why do two functions have the same address?(为什么两个函数的地址相同?)
为什么 std::function 的初始化程序必须是可复制构Why the initializer of std::function has to be CopyConstructible?(为什么 std::function 的初始化程序必须是可复制构造的?)
混合模板与多态性mixing templates with polymorphism(混合模板与多态性)
我什么时候应该使用关键字“typename"?使用模When should I use the keyword quot;typenamequot; when using templates(我什么时候应该使用关键字“typename?使用模板时)
依赖名称解析命名空间 std/标准库Dependent name resolution amp; namespace std / Standard Library(依赖名称解析命名空间 std/标准库)
gcc 可以编译可变参数模板,而 clang 不能gcc can compile a variadic template while clang cannot(gcc 可以编译可变参数模板,而 clang 不能)