Re: References get lost coming out of parser.

Dan Bloomquist <[email protected]> Mon, 25 Nov 2019 08:36:50 -0800
Newsgroups gmane.comp.parsers.spirit.general
Message-ID <[email protected]>
Dan Bloomquist wrote:
> The 'push_op' lambda is the one that gets messed and it is the one 
> that comes from op_type_ :symbols<rpn::funct_op>. So I'm pretty sure 
> that even if I pass it references, it is making copies that disappear...

Well, the solution was pretty simple. I just won't keep a reference to 
the function in 'op', I'll take a copy. See the commented in 'item'. The 
below reproduces my challenge by moving the comment.
On the other hand, I would think there is a way to pass references. I do 
see T& in symbols but it gets messed by the deference even with 
std::ref. Over my head for now!
Best, Dan.

#include <iostream>
#include <functional>
#include <boost/fusion/adapted/struct.hpp>
#include <boost/spirit/home/x3.hpp>

struct item_t{};
using funct_op = void(*)();
const funct_op& first = []() {std::cout << "the first\n"; };
const static funct_op second = []() {};

struct test_ {
     const std::string name;
     const funct_op& op;
}const test[] = {
     {"first", first },
     {"second", second },
};
const test_* test_end = test + sizeof(test) / (sizeof(test_) + 1);

struct item {
     item(const funct_op& op) :op(op) {}
     //const funct_op& op;
     const funct_op op;
     void operator()() { op(); }
};
using item_vect = std::vector<item>;
struct the_attr {
     item_vect items;
     void add_op(funct_op& op) { items.push_back(item(op)); }
};
using namespace boost::spirit::x3;

auto const parseit = rule<struct _, the_attr>{} = [] {
     struct op_type_:symbols<funct_op>{} op_type;
     std::for_each(test, test_end, [&op_type](const test_& t) 
{op_type.add(t.name, t.op); });
     auto const push_op = [](auto& ctx) {_val(ctx).add_op(_attr(ctx)); };
     return op_type[push_op];
}();

int main() {
     std::string str("first");
     auto first(str.begin());
     the_attr att;
     phrase_parse(first, str.end(), parseit, space, att);
     att.items.back()();
     return 0;
}


_______________________________________________
Spirit-general mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/spirit-general