1

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?

WaterFox
  • 850
  • 6
  • 18

1 Answers1

1

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)

sehe
  • 374,641
  • 47
  • 450
  • 633
  • Wahoo super clear thank you @sehe! If the code compiles, it means that the overload resolution worked as expected, right? Meaning I can expect the compiler to hint me about using `lit` or `as_parser` ? – WaterFox Nov 15 '22 at 19:27
  • 1
    Yes in practice. Of course in perfidious scenarios you can imagine foreign overloads interfering in a way that generates valid parser expressions with unexpected meaning, but I can't see that happening unless you do it on purpose. – sehe Nov 15 '22 at 21:31