看到这个问题,Best STL transform - like template function for ternary operators,认为对于踢腿和傻笑进行一次改编是很酷的。
所以我把它扔在一起,似乎工作......有一个空洞。我的preincrement方法对我来说很奇怪。没有拆包,我无法弄清楚如何处理。我希望语法类似(++args)...
(类似于(*args)...
的deference语法),但会返回错误。有谁知道怎么做?
#include <iostream>
#include <vector>
inline void preincrement(){}
template <typename T,typename... Ts>
inline void preincrement(T& t,Ts&... ts)
{
++t;
preincrement(ts...);
}
template <class OutputIterator, class NArryOperator, class InputIterator, class... InputIterators>
OutputIterator transform_n(OutputIterator out_iter, NArryOperator oper, InputIterator iter1begin, InputIterator iter1end,InputIterators... args)
{
for (; iter1begin != iter1end; ++out_iter,++iter1begin,preincrement(args...))
{
*out_iter = oper(*iter1begin,(*args)...);
}
return out_iter;
}
template <typename T>
struct noop
{
T operator()(const T& val){return val;}
};
template <typename Ot,typename T,typename... Ts>
struct nsum
{
Ot operator()(const T& t,const Ts&... ts)
{
return (Ot)t+nsum<Ot,Ts...>()(ts...);
}
};
template <typename Ot, typename T>
struct nsum<Ot,T>
{
Ot operator()(const T& t)
{
return (Ot)t;
}
};
int main(int argc,char** argv)
{
std::vector<int> rng;
for (int i = 0; i < 10; i++) {rng.push_back(i);}
std::vector<int> rng1 = rng;
std::vector<int> rng2 = rng;
std::vector<int> rng3 = rng;
std::vector<float> out(rng.size());
auto beg = out.begin();
auto end = transform_n(beg,nsum<double,int,int,int,int>(),
rng.begin(),rng.end(),
rng1.begin(),
rng2.begin(),
rng3.begin());
for (auto i = beg; i != end; ++i)
{
std::cout << *i << std::endl;
}
}
答案 0 :(得分:2)
直接使用后增量的解决方案:
template <class OutputIterator, class NArryOperator,
class InputIterator, class... InputIterators>
OutputIterator transform_n(OutputIterator out_iter, NArryOperator oper,
InputIterator iter1begin, InputIterator iter1end,
InputIterators... args)
{
while(iter1begin != iter1end)
{
*out_iter++ = oper(*iter1begin++, (*args++)...);
}
return out_iter;
}
关于递增for语句的“increment-expression”:
你不能扩展for-statement的“increment-expression”;包扩展仅限于几个上下文,因此operator,
重载不能应用[temp.variadic] / 4。通常的技巧是必需的,例如扩展函数调用(使用的是什么)或使用虚拟数组:
using iarr = int[];
for (; iter1begin != iter1end;
++out_iter,++iter1begin,(void)iarr{0, (++args,void(),0)...})