I am beginning with Boost Spirit x3 parsing library - and I'm very excited about it.
One thing unclear to me is when and why one should use x3::lit
.
From what I understood, it's because we can not expect an expression like ']' >> double_
to be interpreted as intended within C syntactic rules.
But my interpretation seems incorrect, since the official documentation displays numerous examples of simple strings followed by the >>
operator, and others instances where parenthesis and/or brackets have to be specified as lit(']')
What am I missing?
CodePudding user response:
You can not generally expect '[' >> x
to see the X3 expression overload.
Overload resolution depends on the types of both operands. Since '[
' is char, there cannot be user-defined overloads. So in this case, only if x
is already an x3 parser expression the x3 overload of operator>>
will be found.
In generic code, if both operands are unknown you should use x3::as_parser
instead of x3::lit
because it will leave other types of expressions intact, but promotes string literals like you would expect:
auto combine(auto a, auto b) {
return x3::as_parser(a) >> x3::as_parser(b);
}
The mechanism for overload resolution at play in e.g. 'x' >> x3::double_
is ADL: https://en.cppreference.com/w/cpp/language/adl (Incidentally it's the same mechanism that makes std::cout << "Hello world\n"
find the std::operator>>
overload)