[英]Why can't the compiler deduce template parameter from return type?
Given the following code 给出以下代码
#include <vector>
#include <memory>
using namespace std;
class MyBase
{};
class MyDerived : public MyBase
{};
template<class Base, class Derived>
vector<Base> makeBaseVec(const Derived& obj, const typename vector<Base>::size_type size)
{
vector<Base> out;
for (typename vector<Base>::size_type i = 0; i < size; i++)
{
out.push_back(Base(obj) /* copy constructor */);
}
return out;
}
int main()
{
MyDerived a;
vector<MyBase> v = makeBaseVec<MyBase>(a, 10);
}
Why do I get the error 为什么我会收到错误
main.cpp:13:14: note: template argument deduction/substitution failed:
main.cpp:29:41: note: couldn't deduce template parameter 'Base'
vector<MyBase> v = makeBaseVec(a, 10);
^
Shouldn't the compiler be able to deduce the the template parameter Base
from the type of v
? 编译器是否应该能够从
v
的类型中推导出模板参数Base
?
I can rectify this by changing line 27 to 我可以通过改变第27行来纠正这个问题
vector<MyBase> v = makeBaseVec<MyBase>(a, 10);
but this felt unnecessary. 但这感觉不必要。
Shouldn't the compiler be able to deduce the the template parameter Base from the type of
v
?编译器是否应该能够从
v
的类型中推导出模板参数Base?
The type of v
is not considered by the template type deduction mechanism when you call makeBaseVec
. 调用
makeBaseVec
时,模板类型推导机制不考虑v
的类型。 What if you were to call the function and discard the return value? 如果您要调用该函数并丢弃返回值,该怎么办?
Return types do not participate in type deduction or overload resolution. 返回类型不参与类型推导或重载解析。
If you don't want to repeat yourself, you can use type deduction on v
instead: 如果您不想重复自己,可以在
v
上使用类型推导:
auto v = makeBaseVec<MyBase>(a, 10);
In fact, almost always auto
is a good policy for variables. 事实上,几乎所有
auto
都是变量的好政策。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.