问题描述
最明显的答案可能是-因为标准是这样.
很好,但是我想尽办法了解这种选择的原因.
The most obvious answer could be - because the standard says so.
That's fine, but I'm wrapping my head around it to understand the reasons behind this choice.
请考虑以下示例:
template<typename T>
struct S { S(T) {} };
S f() { return 0; }
int main() {
auto s = f();
(void)s;
}
它无法编译并显示以下错误:
It fails to compile with errors like:
很容易修复,这不是问题,类似这样的方法就可以了:
Quite easy to fix, it isn't a problem, something like this works just fine:
auto f() { return S{0}; }
但是,我想了解在函数返回类型中也允许类模板参数推导的缺点.
乍一看,这似乎是一个愚蠢的限制,但是我敢肯定,我在这里错过了一些重要的事情.
However, I'd like to understand what were the drawbacks of allowing class template arguments deduction also in function return types.
At a first glance, it looks just like a silly limitation, but I'm pretty sure I'm missing something important here.
推荐答案
此处没有任何法律限制:如果您指定返回类型(而不是auto
或T
,其中T
是模板类型),该返回类型必须有效.让我给您提供一个更简单,更好的示例:
There's nothing language-lawery here: If you specify a return type (and not auto
or T
where T
is a template type), that return type has to be valid. let me give you even a simpler, better example:
std::vector function() {
return std::vector<int>();
}
很明显,即使没有精美的模板,auto
和类型推导,它也无法编译,因为std::vector
不是类型,std::vector<int>
是.
Obviously it fails to compile, even without fancy templates, auto
and type deductions, because std::vector
isn't a type, std::vector<int>
is.
基本上,当您将S
指定为返回类型时,
When you specify S
as a return type you basically
- 防止编译器推断类型本身
- 指定无效的返回类型,因为
S
不是类型,S<int>
是.
- Prevent the compiler from deducing the type itself
- Specify an invalid return type, as
S
isn't a type,S<int>
is.
这篇关于为什么函数返回类型中不允许参数推导?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!