On Sun, Oct 15, 2023 at 12:00:51PM -0700, Per Bothner wrote:
> I'm far from a C++ expert these days, but some ideas:
>
> * First of course you can define some helper methods:
>
> class TargetElement {
> Extra *extra;
> Command *unit_command() { return extra ? extra->init_command() : nullptr; }
> }
I don't think you can implement this language feature with helper
methods, at least not like this. Consider the chain of access
a->maybe_b()->maybe_c()->d(). If maybe_b() returns null then the ->maybe_c()
call will be an error.
In JavaScript, I believe you could do a.b?.c?.d and if a.b is null or
undefined then the later accesses to c or d won't matter.
If the field names are available at run time, maybe you could implement it
with a function called like 'safe_access(a, "b", "c", "d")' but this is
not idiomatic C++. It is also questionable how this would work for array
accesses.
> * Declarations in 'if' statement:
>
> if (auto unit_command = target_elememt->unit_command()) {
> if (unit_command->cmdname() == "node") ...
> }
It's still more verbose.
> * Perhaps use a subclass for the "extra" fields:
>
> class TargetElementWithExtra :: TargetElement {
> Command *unit_command;
> }
>
> if (auto te = dynamic_cast<TargetElementWithExtra*>(target_element)) {
> // te is target_element safely cast to TargetElementWithExtra*.
> }
This would require a lot of extra class definitions and doesn't seem that
easy to read.