問題描述
我有這個代碼:
template<
class T = const int &
> void f(T) {}
void f(const int &) {}
int main() {
f(0);
}
為什么它調(diào)用第二個而不是第一個?我會認為它們是相同的,但它們顯然不是,因為我沒有收到重新定義錯誤.
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.
當模板函數(shù)和非模板函數(shù)都可用于解析函數(shù)調(diào)用時,選擇非模板函數(shù).
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:
[...] 鑒于這些定義,如果對于所有參數(shù) i,ICSi(F1) 不是更差的轉(zhuǎn)換,則可行函數(shù) F1 被定義為比另一個可行函數(shù) F2 更好的函數(shù)序列比ICSi(F2),然后[...] F1是一個非模板函數(shù),F(xiàn)2是一個函數(shù)模板特化 [...]
[...] 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 [...]
這篇關(guān)于為什么具有“相同簽名"的模板和非模板函數(shù)的重載?調(diào)用非模板函數(shù)?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!