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?
>Solution :
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);
.