You keep mentioning pointers but your parse functions don't return pointers to Automaton objects. They simply return Automaton objects. No pointers.
This
1 2 3 4
|
if (auto maybe_a = ParsePrimitive(input))
{
...
}
| |
is the same as
1 2 3 4
|
if (Automaton maybe_a = ParsePrimitive(input))
{
...
}
| |
which is basically the same as
1 2 3 4 5
|
Automaton maybe_a = ParsePrimitive(input);
if (maybe_a)
{
...
}
| |
For this to work
maybe_a needs to be convertible to bool. Pointers and integers (including chars) are convertible to bool but struct types are not convertible to bool by default. By defining an
operator bool()
you can make it convertible to bool but is this what you want?
If you want the parse functions to return pointers you should change the return type of your parse functions and instead return pointers (preferably smart pointers). Then you could return
nullptr if the parsing failed which would be treated as false by the if statement.
If you want to define an
operator bool()
you should think about what it means for an Automaton to be "false". The example code that you found used
col but Automaton doesn't contain a member with that name so instead you would probably want to use
initial_state and/or
final_state to decide whether the object is "false" or not.
Another option is to return a
std::optional<Automaton>
.
I noticed that many of your parse functions call
syntax_error()
without returning anything afterwards. This could be fine if
syntax_error()
throws an exception (or terminates the program immediately), but if it returns normally and the function ends without returning anything you're in trouble because reaching the end of a non-void function leads to undefined behaviour.
If the parse functions throw exceptions then you would check that with a try-catch statement. In that case you probably don't need to check the result of the parse functions with an if statement.