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

How to send a named function to a boost::phoenix expression

本文关键字:boost phoenix 表达式 函数      更新时间:2023-10-16

我不知道如何将一个命名函数作为参数发送到另一个函数,并将该参数包含在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版本。这个工作得很好,但是,我想让它与phoenix一起工作,因为我不能使用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);
}

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

#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);
}