Filling std :: [container] from a function by passing an output iterator

I want to fill a container inside a function by passing an output iterator, since this is the most efficient way to do this, as I understand it. eg.

template <typename OutputIterator> void getInts(OutputIterator it) { for (int i = 0; i < 5; ++i) *it++ = i; } 

( Is returning std :: list expensive? )

But how can I apply the type that the iterator should refer to? Basically I want to say that "this function accepts an output iterator of type boost :: tuple".

+4
source share
2 answers

You can use boost :: enable_if in combination with std: iterator_traits :

 #include <boost/type_traits/is_same.hpp> #include <boost/utility/enable_if.hpp> template <typename OutputIterator> typename boost::enable_if< boost::is_same< int, /* replace by your type here */ typename std::iterator_traits<OutputIterator>::value_type > >::type getInts(OutputIterator it) { for (int i = 0; i < 5; ++i) *it++ = i; } 
+5
source

You do not need. In any case, the code will not compile if the caller passes the wrong type of iterator.

So, this is already mandatory for you.

+2
source

Source: https://habr.com/ru/post/1333453/


All Articles