I was trying to insert a data struct into a vector everytime a match is detected, but i am failing even in compiling. The code is next:
#include <string>
#include <boost/xpressive/xpressive.hpp>
#include <boost/xpressive/regex_actions.hpp>
using namespace boost::xpressive;
struct Data
{
int integer;
double real;
std::string str;
Data(const int _integer, const double _real, const std::string& _str) : integer(_integer), real(_real), str(_str) { }
};
int main()
{
std::vector<Data> container;
std::string input = "Int: 0 - Real: 18.8 - Str: ABC-1005\nInt: 0 - Real: 21.3 - Str: BCD-1006\n";
sregex parser = ("Int: " >> (s1 = _d) >> " - Real: " >> (s2 = (repeat<1,2>(_d) >> '.' >> _d)) >> " - Str: " >> (s3 = +set[alnum | '-']) >> _n)
[::ref(container)->*push_back(Data(as<int>(s1), as<double>(s2), s3))];
sregex_iterator cur(input.begin(), input.end(), parser);
sregex_iterator end;
for(; cur != end; ++cur)
smatch const &what = *cur;
return 0;
}
It is failing in compile the "push_back" semantic action due to I am using a Data object inside and it is not able to use it lazinessly (I guess, I am not really sure).
Please, could anyone help me with this?
Note- I am unluckily tied to MS VS 2010 (not fully c++11 compliant), so please don't use variadic templates and emplace_back solutions. Thank you.
Using Xpressive
You should make the action a lazy actor. Your
Dataconstructor call isn't.Live On Coliru
Prints
Using Spirit
I'd use spirit for this. Spirit has the primitives to directly parse to underlying data types, which is less error prone and more efficient.
Spirit Qi (V2)
Using Phoenix, it's pretty similar: Live On Coliru
Using Fusion adaptation, it gets more interesting, and a lot simpler:
Live On Coliru
Now imagine:
How would you do that in Xpressive? Here's how you'd do it with Spirit. Note how the additional constraints do not change the grammar, essentially. Contrast that with regex-based parsers.
Live On Coliru
Still prints
Further thoughts: how would you
Spirit X3
If you can use c++14, Spirit X3 can be more efficient, and compile a lot faster than either the Spirit Qi or the Xpressive approach:
Live On Coliru
Prints (it's getting boring):