通过传递输出迭代器从函数填充std :: [容器]

fgu*_*gor 4 c++ templates iterator

我想通过传递输出迭代器从函数内部填充容器,因为这是我理解的最有效的方法.例如

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

(返回std :: list代价高昂吗?)

但是我如何强制执行类型,迭代器应该指向?基本上我想说"这个函数采用boost :: tuple类型的输出迭代器".

ice*_*ime 5

您可以将boost :: enable_ifstd: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;
}
Run Code Online (Sandbox Code Playgroud)