如何将命名函数发送到boost :: phoenix表达式

时间:2013-08-28 16:39:40

标签: c++ boost boost-phoenix

我无法弄清楚如何将命名函数作为参数发送到另一个函数,并将参数包含在phoenix lambda表达式中。

这是我能想到的最小例子。

#include <vector>
#include <iostream>
#include <algorithm>
#include <boost/phoenix.hpp>

using namespace std;
namespace ph = boost::phoenix;
using ph::arg_names::arg1;

template <typename Predicate>
void foo(vector<int> &v, Predicate p) {
  for_each(v.begin(), v.end(),
      if_(p(arg1))
      [
        cout << "found " << arg1 << ", "
      ]);
  cout << endl;
}

bool is_odd(int i) {
  return (i % 2 == 1);
}

main() {
  vector<int> v(10);
  int i = 1;
  generate(v.begin(), v.end(), ph::ref(i)++);
  cout << "looking for odd ones ";
  foo(v, arg1 % 2 == 1);

  cout << "using named function ";
  //foo(v, is_odd);
  //foo(v, &is_odd);
  //foo(v, ph::bind(&is_odd, arg1));
  //foo(v, boost::bind(&is_odd, _1));
}

我无法弄清楚如何将is_odd()函数作为谓词发送到foo()

注意: 在我的实际代码中,谓词实际上是arg1的成员函数(arg1class Bar,我需要Bar::is_odd作为谓词)。我尝试过(arg1->*&Bar::is_odd)()样式,但它没有用。为简单起见,我不在此示例中包含此内容。

更新 这是相同代码的C ++ 11版本。这个很好用,但是,我想用凤凰工作,因为我不能用C ++ 11

#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

template <typename Predicate>
void foo(vector<int> &v, Predicate p) {
  for_each(begin(v), end(v),
      [&] (int i) {
        if (p(i))
          cout << "found " << i << ", ";
      });
  cout << endl;
}

bool is_odd(int i) {
  return (i % 2 == 1);
}

main() {
  vector<int> v={1,2,3,4,5,6,7,8,9,10};
  cout << "looking for odd ones ";
  foo(v, [] (int i) {return (i%2 == 1);});

  cout << "using named function ";
  foo(v, &is_odd);
}

1 个答案:

答案 0 :(得分:1)

可能有另一种更简单的方法,但另一种方法是使用凤凰函数(在g ++ 4.8.1上测试,不使用-std = c ++ 11):

#include <vector>
#include <iostream>
#include <algorithm>
#include <boost/phoenix.hpp>

using namespace std;
namespace ph = boost::phoenix;
using ph::arg_names::arg1;

bool is_odd(int i) {
  return (i % 2 == 1);
}

struct is_odd_impl
{
  template <typename Sig>
  struct result;

  template <typename This, typename Arg>
  struct result<This(Arg)>
  {
    typedef bool type;
  };

  template <typename Arg>
  bool operator()(const Arg& arg) const
  {
    return is_odd(arg);
    //return arg.is_odd();
  }
};

ph::function<is_odd_impl> lazy_is_odd = is_odd_impl();

template <typename Predicate>
void foo(vector<int> &v, Predicate p) {
  for_each(v.begin(), v.end(),
      if_(p(arg1))
      [
        cout << "found " << arg1 << ", "
      ]);
  cout << endl;
}



int main() {
  vector<int> v(10);
  int cont = 1;
  std::generate(v.begin(),v.end(),ph::ref(cont)++);

  cout << "looking for odd ones ";
  foo(v, arg1 % 2 == 1);

  cout << "using named function ";
  foo(v, lazy_is_odd);
}