Search code examples
c++boost-spiritboost-spirit-qi

Boost.Spirit semantic action to parse a string does not work


I try to write a Boost.Spirit parser that parses a string that should represent a simple command like "print foo.txt". Each time the input fulfills the grammar a semantic action should be called.

Here is the code:

template<class Iterator>
struct my_parser : qi::grammar<Iterator, void(), qi::ascii::space_type>
{
    void test(std::string const & s) const
    {
        std::cerr << s << std::endl;
    }

    my_parser() : my_parser::base_type(print)
    {
        using qi::_1;
        using qi::char_;

        filename =
            *qi::char_("a-zA-Z_0-9./ ")
            ;

        print =
            qi::lit("print")
            >> filename [ boost::bind(&my_parser::test, this, _1) ]
            ;
    }

    qi::rule<Iterator, std::string()> filename;
    qi::rule<Iterator, void(), qi::ascii::space_type> print;
};

If I try to compile this I get something like:

no match for call to ‘(const boost::_mfi::cmf1<void, parser::my_parser<__gnu_cxx::__normal_iterator<const char*, std::basic_string<char> > >, const std::basic_string<char>&>) (parser::my_parser<__gnu_cxx::__normal_iterator<const char*, std::basic_string<char> > >* const&, const boost::phoenix::actor<boost::spirit::argument<0> >&)’

If I replace _1 with "abc" for example the code compiles but phrase_parse() return with false for the input "print foo.txt". If I comment out the [ boost:bind(...) ] phrase_parse() return with true.

Does anyone know what I do wrong? Thanks.


Solution

  • I believe your problem is that you're trying to pass a spirit placeholder to boost::bind, which generally only works with its built in placeholders ( which you've hidden with using qi::_1 ). I would try adding the define BOOST_SPIRIT_USE_PHOENIX_V3, add #include "boost/phoenix.hpp" and then go for boost::phoenix::bind(&my_parser::test, this, _1 ) instead.