How can I also include function bodies in a transformation of a Boost Phoenix expression?
For example, I have built on the Lazy Functions section of the Boost Phoenix Starter Kit, and created a lazy addition function:
struct my_lazy_add_impl {
typedef int result_type;
template <typename T>
T operator()(T x, T y) const { return x+y; }
};
phoenix::function<my_lazy_add_impl> my_add;
I then prepare a simple plus-to-minus transform from a previous question, shown here:
struct invrt:
proto::or_<
proto::when<
proto::plus<proto::_, proto::_>,
proto::functional::make_expr<proto::tag::minus>(
invrt(proto::_left), invrt(proto::_right)
)
>,
proto::otherwise<
proto::nary_expr<proto::_, proto::vararg<invrt> >
>
>
{};
However, when I apply an inverted Phoenix lambda
expression, using my_add
, to its arguments, as shown below, it seems the intended inversion has not been achieved. Is there a recommended way to implement function calls within Phoenix, which can facilitate such transformations?
int main(int argc, char *argv[])
{
auto f = phoenix::lambda(_a = 0)[my_add(_1,_2)];
auto g = invrt()(phoenix::lambda(_a = 0)[my_add(_1,_2)]);
std::cout << f()(1,2) << std::endl; // 3
std::cout << g()(1,2) << std::endl; // 3 again; alas not -1
return 0;
}
The answer is really very simple and you're going to kick yourself. The expression transformation you wrote knows how to convert a plus node into a subtract node. But there is no plus node in the expression you're passing to it. Look again:
auto g = invrt()(phoenix::lambda(_a = 0)[my_add(_1,_2)]);
Where's the plus node? To Proto (and to Phoenix), my_add
is opaque. They don't know there's an addition going on inside there. How could they?
====EDIT====
Consider this instead, which does what you intend:
#include <iostream>
#include <boost/phoenix.hpp>
#include <boost/proto/proto.hpp>
namespace proto = boost::proto;
namespace phoenix = boost::phoenix;
using namespace phoenix::arg_names;
using namespace phoenix::local_names;
auto const my_add = phoenix::let(_a = _1, _b = _2)[_a + _b];
struct invrt:
proto::or_<
proto::when<
proto::plus<proto::_, proto::_>,
proto::functional::make_expr<proto::tag::minus>(
invrt(proto::_left), invrt(proto::_right)
)
>,
proto::otherwise<
proto::nary_expr<proto::_, proto::vararg<invrt> >
>
>
{};
int main()
{
auto f = phoenix::lambda(_a = 0)[my_add(_1,_2)];
auto g = invrt()(phoenix::lambda(_a = 0)[my_add(_1,_2)]);
std::cout << f()(1,2) << std::endl; // 3
std::cout << g()(1,2) << std::endl; // -1, w00t!
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With