Why is the compiler not selecting my function-template overload in the following example?

Posted by Steve Guidi on Stack Overflow See other posts from Stack Overflow or by Steve Guidi
Published on 2009-10-14T17:37:07Z Indexed on 2010/05/06 0:28 UTC
Read the original article Hit count: 583

Given the following function templates:

#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)
{
};

Why is it that the following code always invokes overload #1 instead of overload #2?

void main()
{
    std::vector<std::pair<int, int> > v;
    Derived derived;

    f(100, 200);  // clearly calls overload #1
    f(v, &derived);         // always calls overload #1
}

Given that the second parameter of f is a derived type of Base, I was hoping that the compiler would choose overload #2 as it is a better match than the generic type in overload #1.

Are there any techniques that I could use to rewrite these functions so that the user can write code as displayed in the main function (i.e., leveraging compiler-deduction of argument types)?

© Stack Overflow or respective owner

Related posts about c++

Related posts about function-templates