【发布时间】:2013-07-21 21:19:09
【问题描述】:
通常我不能使用 std::for_each 因为我对特定元素的逻辑取决于它的当前索引。为此,我发明了一个函子类,它包装了主函子并将当前索引传递给它。理想情况下,我想将它与 lambda 表达式一起使用。我创建的课程安全有效吗?有没有更好的解决方案?我确实希望包装器的运算符 () 返回 lambda 表达式的类型,但我无法弄清楚。另外,我应该为索引使用什么类型?我应该通过值还是引用将主函子存储在包装器中?
谢谢!
template<class FUNC>
class IndexFunctor
{
public:
typedef FUNC FUNC_T;
explicit IndexFunctor(const FUNC_T& func) : func(func), index(0) {}
// how can this return the return type of func?
template<class T>
void operator ()(T& param)
{
func(index++, param);
}
const FUNC_T& GetFunctor() const
{
return func;
}
int GetIndex() const
{
return index;
}
void SetIndex(int index)
{
this->index = index;
}
private:
FUNC_T func;
int index;
};
template<class FUNC>
IndexFunctor<FUNC> with_index(const FUNC& func)
{
return IndexFunctor<FUNC>(func);
}
void somefunc()
{
std::vector<int> v(10);
std::for_each(v.begin(), v.end(), with_index([](int index, int x){ std::cout << "[" << index << "]=" << x << std::endl; }));
}
【问题讨论】:
-
其中一些问题可能更适合Code Review。
-
为什么不直接使用
for循环呢?我不觉得std::for_each有帮助,而且我通常对使用算法无处不在而不是循环感到厌烦。 -
我无法谈论 Neil 的情况,但在您有一对迭代器但无法获得范围大小但仍需要索引的情况下,它可能很有用。当然,这是一种罕见的情况,但你永远不会知道。