2
votes

such are the codes:

template<typename T>
struct ST{
ST();
ST(T t){}
};
template<typename T>
void fun(ST<T> t, T a){
}

int main(int argc, char * argv[])
{
  ST<int> t=2;
   fun(2,2);
}

compile with g++ 4.8.2 errinfo:

no matches for fun(int,int)

Candidate is:

template void fun(ST, T)

template argument deduction/substitution failed:

mismatched types ‘ST’ and ‘int’

3

3 Answers

1
votes

Try:

template<class T>struct identity{typedef T type;};
template<class T>void fun(typename identity<S<T>>::type s, T t)

this will block the compiler from trying to do argument type deduction on the first argument.

template type matching is pattern matching. Few conversions are done, as in the general case it cannot be solved (is there a T such that X<T> can be converted from type Z is Turing-complete up to arbitrary limits of template compilers: recursion depth etc).

In C++11 you can do:

template<class T>struct identity{typedef T type;};
template<class T>suing identity_t = typename identity<T>::type;
template<class T>void fun(identity_t<S<T>> s, T t)

which I find cleaner (moves boilerplate away from other code).

2
votes

Implicit type conversions are not used for deducing template arguments, you have to manually specify the type in this case fun<int>(2,2);

1
votes

Your function signature is void fun(ST<T> t, T a), but you call the function with fun(int, int). Just like your error says, these do not match. If the type deduction for fun was int, the signature would look like: fun(ST<int> t, int a), you would call it with fun(t, 2).