Search code examples
c++11templatestype-deduction

Couldn't deduce second template parameter of method from template class


Take the following example:

template < class T > struct Dummy
{
    typedef const T & type;
};

struct Type
{
    int i = 0;

    bool operator == (const Type & o) { return i == o.i; }
};

template < class T > struct Test
{
    template < class U >
    bool F(typename Dummy< T >::type a, typename Dummy< U >::type b) const
    {
        return a == b; // dummy operation
    }
};

int main()
{
    Type a, b;
    // error: no matching function for call to 'Test<Type>::F(Type&, Type&)'
    // note: template argument deduction/substitution failed:
    // note: couldn't deduce template parameter 'U'
    bool x = Test<Type>{}.F(a, b);
}

I get an error from the compiler that the second parameter of the method couldn't be deduced. What am I doing wrong here?


Solution

  • Such type deduction is not possible. A class on the left-hand side :: is a non-deduced context for template parameters.

    The reason is simple: the compiler would have to try all possible Us and see if for any of them, Dummy<U> has a nested type that matches what was supplied as the argument. Remember that template specialisation exists! It would be perfectly possible from you to specialise Dummy<int*****> so that its Dummy<int*****>::type is Type.