I can't figure out how to send a named function as an argument to another function, and include the argument in a phoenix lambda expression.
Here's the minimal example that I could think of.
#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));
}
I can't figure out how to send the is_odd()
function to foo()
as a predicate.
Note:
In my actual code the predicate is actually a member function of arg1
(arg1
is of class Bar
, and I need Bar::is_odd
as predicate). I've tried the (arg1->*&Bar::is_odd)()
style but it didn't work. I'm not including this in this example for simplicity.
Update: Here's the C++11 version of the same code. This one works well, however, I'd like to make it work with phoenix, as I can't use 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);
}
There may be another, simpler, way to do this, but one alternative is using a phoenix function(tested on g++ 4.8.1 without -std=c++11):