[英]populating an std::[container] from a function by passing an output iterator
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. 我想通过传递输出迭代器从函数内部填充容器,因为据我所知,这是最有效的方法。 eg
例如
template <typename OutputIterator>
void getInts(OutputIterator it)
{
for (int i = 0; i < 5; ++i)
*it++ = i;
}
( Is returning a std::list costly? ) ( 返回std :: list是否代价高昂? )
But how can I enforce the type, the iterator should point to ? 但是,如何强制迭代器应指向的类型呢? Basically I want to say "this function takes an output iterator of type boost::tuple" .
基本上我想说“此函数采用类型为boost :: tuple的输出迭代器”。
You can use boost::enable_if in conjunction with std:iterator_traits : 您可以将boost :: enable_if与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;
}
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. 所以已经为您执行了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.