给定以下函数模板:
#include <vector>
#include <utility>
struct Base { };
struct Derived : Base { };
// #1
template <typename T1, typename T2>
void f(const T1& a, const T2& b)
{
};
// #2
template <typename T1, typename T2>
void f(const std::vector<std::pair<T1, T2> >& v, Base* p)
{
};
为什么下面的代码总是调用重载#1 而不是重载#2?
int main()
{
std::vector<std::pair<int, int> > v;
Derived derived;
f(100, 200); // clearly calls overload #1
f(v, &derived); // always calls overload #1
return 0;
}
鉴于 of 的第二个参数f
是 的派生类型Base
,我希望编译器会选择重载 #2,因为它比重载 #1 中的泛型类型更匹配。
是否有任何技术可以用来重写这些函数,以便用户可以编写main
函数中显示的代码(即,利用编译器推导参数类型)?