英文:
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 <vector>
#include <iterator>
int main() {
std::vector<int> 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:
<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};
|
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<Container>
实例的 函数:
template< class Container >
constexpr std::back_insert_iterator<Container> back_inserter( Container& 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<Container>
instance:
template< class Container >
constexpr std::back_insert_iterator<Container> back_inserter( Container& 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);
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论