【问题标题】:any stl/boost functors to call operator()任何调用 operator() 的 stl/boost 函子
【发布时间】:2010-06-16 20:15:25
【问题描述】:
template <typename T>
struct Foo
{
    void operator()(T& t) { t(); }
};

是否有任何具有类似实现的标准或提升函子?

我需要它来迭代函子容器:

std::for_each(beginIter, endIter, Foo<Bar>());

或者也许有其他方法可以做到这一点?

【问题讨论】:

  • 我不确定您要的是什么。您的代码原样有什么问题?它应该做什么?
  • 我有 boost::function 对象的容器。我希望用 std::for_each 对其进行迭代,并为每个 boost::function 元素调用 operator() ;我很想知道像 Foo 这样的仿函数是否已经在 stl/boost 中实现了。当然,写出来也没什么大不了的。只是认为它可能已经实现了

标签: c++ boost stl


【解决方案1】:

像 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()));

【讨论】:

    【解决方案2】:

    BOOST_FOREACH 可能会稍微不那么啰嗦,尤其是如果你有 C++0x 的自动支持:

    BOOST_FOREACH(auto f, v) {f();}
    

    【讨论】:

      【解决方案3】:

      至少我找到了。 boost::apply 应该做所有的工作

      std::for_each(beginIter, endIter, boost::bind(boost::apply<void>(), _1));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-02-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多