gpt4 book ai didi

c++ - 无法推导模板参数

转载 作者:行者123 更新时间:2023-12-04 04:02:09 25 4
gpt4 key购买 nike

我不明白为什么在这种情况下不能推导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);
}

从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

当然,以下作品:
DoSomething<MyOtherType>(obj);

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

最佳答案

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

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

Non-deduced contexts

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) 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在其他地方也不为人所知,因此该模板函数将被忽略。

关于c++ - 无法推导模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48387973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com