Template parameter cannot be displayed.

I do not understand why T cannot be deduced in this scenario:

template<class T> class MyType { T * data; }; class MyOtherType { }; template<typename T> struct MyType_OutArg { typedef MyType<T> & type; }; template<typename T> void DoSomething(typename MyType_OutArg<T>::type obj) { } void func(MyType_OutArg<MyOtherType>::type obj) { DoSomething(obj); } 

From GCC 4.7.1 with -std = C ++ 14

 <source>: In function 'void func(MyType_OutArg<MyOtherType>::type)': 26 : <source>:26:20: error: no matching function for call to 'DoSomething(MyType<MyOtherType>&)' DoSomething(obj); ^ 26 : <source>:26:20: note: candidate is: 19 : <source>:19:1: note: template<class T> void DoSomething(typename MyType_OutArg<T>::type) DoSomething(typename MyType_OutArg<T>::type obj) ^ 19 : <source>:19:1: note: template argument deduction/substitution failed: 26 : <source>:26:20: note: couldn't deduce template parameter 'T' DoSomething(obj); ^ Compiler returned: 1 

Of course, the following works:

 DoSomething<MyOtherType>(obj); 

but I'm not sure why this is necessary. Should the compiler have enough information?

+7
c ++ templates
source share
1 answer

This is because your case is in computable contexts.

Quoted from http://en.cppreference.com/w/cpp/language/template_argument_deduction :

Impossible Contexts

In the following cases, the types, patterns, and non-type values โ€‹โ€‹that are used to compose P do not participate in the output of the template argument, but instead use template arguments that were either output elsewhere or explicitly specified. If the template parameter is used only in non-output contexts and is not explicitly specified, the template argument is not output.

1) The nested qualifier name (everything to the left of the scope operator: :) of the type that was specified using the identifier

In your case, typename MyType_OutArg<T>::type will not participate in type inference, and T not known from other sources, so this template function is ignored.

+6
source share

All Articles