hu wang
hu wang

Reputation: 421

with template constructor,template argument deduction/substitution failed,why?

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’

Upvotes: 3

Views: 1058

Answers (3)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275500

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).

Upvotes: 2

user657267
user657267

Reputation: 21000

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

Upvotes: 2

yizzlez
yizzlez

Reputation: 8805

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).

Upvotes: 0

Related Questions