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

前端 未结 2 1742
情歌与酒
情歌与酒 2021-01-20 01:02

I want to populate a container from inside a function by passing an output iterator as this is the most efficient way to do it as I understand. e.g.

template         


        
相关标签:
2条回答
  • 2021-01-20 01:34

    You can use boost::enable_if in conjunction 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;
    }
    
    0 讨论(0)
  • 2021-01-20 01:39

    You don't need to. The code will fail to compile anyway if the caller passes the wrong iterator type.

    So it's enforced for you already.

    0 讨论(0)
提交回复
热议问题