无法推导出模板参数

use*_*078 9 c++ templates

我不明白为什么在这种情况下无法推断出T:

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);
}
Run Code Online (Sandbox Code Playgroud)

从GCC 4.7.1和-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
Run Code Online (Sandbox Code Playgroud)

当然以下工作:

DoSomething<MyOtherType>(obj);
Run Code Online (Sandbox Code Playgroud)

但我不确定为什么这是必要的.编译器不应该有足够的信息吗?

lll*_*lll 8

这是因为您的案例是非推断的上下文.

引自http://en.cppreference.com/w/cpp/language/template_argument_deduction:

非推断的上下文

在下列情况下,用于组成P的类型,模板和非类型值不参与模板参数推导,而是使用在别处推导或显式指定的模板参数.如果模板参数仅在非推导的上下文中使用且未明确指定,则模板参数推断将失败.

1)嵌套名称说明符(范围解析运算符左侧的所有内容::)使用qualified-id指定的类型

在您的情况下,typename MyType_OutArg<T>::type不会参与类型推导,并且T从其他地方不知道,因此忽略此模板函数.