【问题标题】:Automatically deducing the type of bind1st(mem_fun(&my_class::f), this)?自动推导出bind1st(mem_fun(&my_class::f), this)的类型?
【发布时间】:2011-06-13 17:34:41
【问题描述】:

我想将bind1st(mem_fun(&my_class::f), this) 函子传递给for_each。不幸的是,它很难阅读,所以我想给它起一个更易读的名字:

(the type I am looking for) meaningful_name = bind1st(mem_fun(&my_class::f), this);

for_each(v.begin(), v.end(), meaningful_name);

有没有一种简单的方法来推断函子的类型? (我知道mem_fun 正是因为这个原因为我们节省了很多痛苦。)

【问题讨论】:

    标签: c++ templates stl functional-programming functor


    【解决方案1】:

    这取决于 my_class:f 的参数和返回类型。如果函数是

    T my_class::f(A arg)
    

    那么你需要

    binder1st<mem_fun1_t<T,my_class,A> > meaningful_name = bind1st(mem_fun(&my_class::f), this);
    

    这种事情用 C++0x 会更好:

    auto meaningful_name = bind1st(mem_fun(&my_class::f), this);
    

    【讨论】:

    • 差不多:应该是mem_fun1_t,而不是mem_fun1_1
    【解决方案2】:

    不,没有简单的方法。类型名称将相当长,甚至更不可读。如果你使用 boost,你不需要使用BOOST_AUTO,因为你可以使用boost::bind 并让它可读,而不需要本地。

    for_each(v.begin(), v.end(), boost::bind(&my_class::f, this));
    

    【讨论】:

      猜你喜欢
      • 2023-03-30
      • 2011-02-24
      • 1970-01-01
      • 1970-01-01
      • 2016-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多