Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to send a named function to a boost::phoenix expression
    text
    copied!<p>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.</p> <p>Here's the minimal example that I could think of.</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;vector&gt; #include &lt;iostream&gt; #include &lt;algorithm&gt; #include &lt;boost/phoenix.hpp&gt; using namespace std; namespace ph = boost::phoenix; using ph::arg_names::arg1; template &lt;typename Predicate&gt; void foo(vector&lt;int&gt; &amp;v, Predicate p) { for_each(v.begin(), v.end(), if_(p(arg1)) [ cout &lt;&lt; "found " &lt;&lt; arg1 &lt;&lt; ", " ]); cout &lt;&lt; endl; } bool is_odd(int i) { return (i % 2 == 1); } main() { vector&lt;int&gt; v(10); int i = 1; generate(v.begin(), v.end(), ph::ref(i)++); cout &lt;&lt; "looking for odd ones "; foo(v, arg1 % 2 == 1); cout &lt;&lt; "using named function "; //foo(v, is_odd); //foo(v, &amp;is_odd); //foo(v, ph::bind(&amp;is_odd, arg1)); //foo(v, boost::bind(&amp;is_odd, _1)); } </code></pre> <p>I can't figure out how to send the <code>is_odd()</code> function to <code>foo()</code> as a predicate. </p> <p><strong>Note:</strong> In my actual code the predicate is actually a member function of <code>arg1</code> (<code>arg1</code> is of <code>class Bar</code>, and I need <code>Bar::is_odd</code> as predicate). I've tried the <code>(arg1-&gt;*&amp;Bar::is_odd)()</code> style but it didn't work. I'm not including this in this example for simplicity.</p> <p><strong>Update:</strong> 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</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;vector&gt; #include &lt;iostream&gt; #include &lt;algorithm&gt; using namespace std; template &lt;typename Predicate&gt; void foo(vector&lt;int&gt; &amp;v, Predicate p) { for_each(begin(v), end(v), [&amp;] (int i) { if (p(i)) cout &lt;&lt; "found " &lt;&lt; i &lt;&lt; ", "; }); cout &lt;&lt; endl; } bool is_odd(int i) { return (i % 2 == 1); } main() { vector&lt;int&gt; v={1,2,3,4,5,6,7,8,9,10}; cout &lt;&lt; "looking for odd ones "; foo(v, [] (int i) {return (i%2 == 1);}); cout &lt;&lt; "using named function "; foo(v, &amp;is_odd); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload