編譯器使用模板版本來計算t = max(a, b)
和max(t, c)
。標準支持的任何引用是值得歡迎的。爲什麼模板版本是由編譯器在下面選擇的?
#include <iostream>
template <typename T>
inline T const& max (T const& a, T const& b)
{
std::cout << "template" << '\n';
return a < b ? b : a;
}
template <typename T>
inline T const& max (T const& a, T const& b, T const& c)
{
return max (max(a,b), c);
}
inline int const& max (int const& a, int const& b)
{
std::cout << "non-template" << '\n';
return a <b ? b : a;
}
int main()
{
std::cout << max(3, 5, 7) << '\n';
}
template
template
7
嘗試在你的3參數'max'前向前聲明'int const&max(int const&a,int const&b)'? – Yakk
@Yakk我知道這將解決問題。但我想知道這是爲什麼? – Alexander
「模板」定義點之後的重載只能通過標準的ADL找到。 'int'不是用戶定義的類型,所以你的ADL不工作(我不知道非用戶定義類型ADL是如何工作的,如果它真的工作的話)。一些編譯器**咳嗽**視覺工作室**咳嗽**不正確地做到這一點(不確定2013年左右)。 – Yakk