template <typename T>
struct Foo
{
void operator()(T& t) { t(); }
};
是否有类似实现的标准或增强仿函数?
我需要它来迭代仿函数容器:
std::for_each(beginIter, endIter, Foo<Bar>());
或者还有其他方法可以做到这一点?
答案 0 :(得分:4)
像Boosts或C ++ 0x bind()
这样的绑定器使生成这样的仿函数变得微不足道:
std::for_each(begin, end, boost::bind(&Bar::operator(), _1));
或使用mem_fun_ref
:
std::for_each(v.begin(), v.end(), std::mem_fun_ref(&Bar::operator()));
答案 1 :(得分:1)
BOOST_FOREACH
可能略逊一筹,特别是如果你有C ++ 0x的自动支持:
BOOST_FOREACH(auto f, v) {f();}
答案 2 :(得分:0)
至少我发现了它。 boost :: apply应该完成所有工作
std::for_each(beginIter, endIter, boost::bind(boost::apply<void>(), _1));