无法推导模板参数 [英] Template parameter cannot be deduced

查看:109
本文介绍了无法推导模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I don't 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);
}

来自GCC 4.7.1,带有-std = c ++ 14

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

当然,以下工作:

DoSomething<MyOtherType>(obj);

但我不确定为什么有必要。

but i'm unsure why it's necessary. Shouldn't the compiler have enough information?

推荐答案

这是因为您的情况是非推论上下文 em>。

This is because your case is a Non-deduced contexts.

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


非推论上下文

Non-deduced contexts

在以下情况下,用于构成P的类型,模板和非类型值不参与模板自变量的推导,而是使用在其他地方推导或明确指定。如果仅在非推导上下文中使用模板参数并且未明确指定模板参数,则模板参数推导将失败。

In the following cases, the types, templates, and non-type values that are used to compose P do not participate in template argument deduction, but instead use the template arguments that were either deduced elsewhere or explicitly specified. If a template parameter is used only in non-deduced contexts and is not explicitly specified, template argument deduction fails.

1)嵌套名称说明符(使用限定ID指定的类型的作用域解析运算符::)的左侧

1) The nested-name-specifier (everything to the left of the scope resolution operator ::) of a type that was specified using a qualified-id

在您的情况下, typename MyType_OutArg< T> :: type 将不参与类型推导,并且在其他地方也不知道 T ,因此此模板功能将被忽略。

In your case, typename MyType_OutArg<T>::type will not participate in type deduction, and T is not known from elsewhere, thus this template function is ignored.

这篇关于无法推导模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆