back_inserter的初始化

huangapple go评论86阅读模式
英文:

Initialization of a back_inserter

问题

如果我取消注释带有 b1 的那一行,gcc 会产生以下错误:

<source>: In function 'int main()':
<source>:6:24: error: unable to deduce 'auto' from 'std::back_inserter'
    6 |         auto b1 = std::back_inserter{v1};
      |                        ^~~~~~~~~~~~~
<source>:6:24: note:   couldn't deduce template parameter 'auto'
<source>:6:37: error: expected ',' or ';' before '{' token
    6 |         auto b1 = std::back_inserter{v1};
      |

而使用带有 b2 的那一行则可以编译成功。

为什么带有 b1 的那一行会产生错误,而带有 b2 的那一行可以编译成功呢?如果可能的话,您可以指向 https://en.cppreference.com 或标准文档中相关的部分吗?

英文:

Consider the following code (live):

#include &lt;vector&gt;
#include &lt;iterator&gt;

int main() {
	std::vector&lt;int&gt; v1 = {1, 2, 3};
	
	// auto b1 = std::back_inserter{v1};
	auto b2 = std::back_inserter(v1);
}

If I uncomment the line with b1, gcc gives the following error:

&lt;source&gt;: In function &#39;int main()&#39;:
&lt;source&gt;:6:24: error: unable to deduce &#39;auto&#39; from &#39;std::back_inserter&#39;
    6 |         auto b1 = std::back_inserter{v1};
      |                        ^~~~~~~~~~~~~
&lt;source&gt;:6:24: note:   couldn&#39;t deduce template parameter &#39;auto&#39;
&lt;source&gt;:6:37: error: expected &#39;,&#39; or &#39;;&#39; before &#39;{&#39; token
    6 |         auto b1 = std::back_inserter{v1};
      |     

Using line with b2, on the other hand, compiles fine.

Why does the line with b1 result in an error, while the line with b2 compiles fine? If possible, can you point me to the relevant documentation in https://en.cppreference.com or in the standard?

答案1

得分: 3

std::back_inserter 是一个返回 std::back_insert_iterator&lt;Container&gt; 实例的 函数

template&lt; class Container &gt;
constexpr std::back_insert_iterator&lt;Container&gt; back_inserter( Container&amp; c );

你不能使用{...} 来调用函数,就像你在 auto b1 = std::back_inserter{v1}; 中尝试的那样。要调用一个函数,需要用 (...) 包围参数,就像你在 auto b2 = std::back_inserter(v1); 中做的那样。

英文:

std::back_inserter is a function that returns a std::back_insert_iterator&lt;Container&gt; instance:

template&lt; class Container &gt;
constexpr std::back_insert_iterator&lt;Container&gt; back_inserter( Container&amp; c );

You can't call functions using {...} as you try doing in auto b1 = std::back_inserter{v1};. To call a function, (...) needs to surround the arguments, as you do it in auto b2 = std::back_inserter(v1);.

huangapple
  • 本文由 发表于 2023年6月25日 21:12:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76550572.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定