Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Initialization of a back_inserter

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading