3

I have some code that depends upon various std::shared_ptr values having been initialized. In the case where one or more of these values have not been initialized, I'd like to just return from the function. What I want is something like this:

class A {};
class B {};
class C {};

std::shared_ptr<A> myA;
std::shared_ptr<B> myB;
std::shared_ptr<C> myC;

void foo()
{
    if (not std::ranges::all_of( {myA, myB, myC}, [](auto&& x) { return bool(x); } ))
    {
        // log that this can't run
        return;
    }
    // do foo
}

This is inspired by my corruption from using Python, where it's simple to write

if not all( (myA, myB, myC) ): return

C++ doesn't quite have the same type of heterogeneous containers as Python, but it's doing a pretty good job of faking it, with initializer lists. Is there a way to express this kind of object-oriented generalization in modern C++?

jwm
  • 1,504
  • 1
  • 14
  • 29

1 Answers1

2

Presumably, you are looking for generic (variadic) solution:

    if(not std::apply([](auto&...es) {return (es &&...);}, std::tie(myA, myB, myC)) ) {
        // log that this can't run
        return;
    }

of course, if you have the 3 objects explicitly, it is better to do if(not(myA && myB && myC)) {.

https://godbolt.org/z/eKMfE48Gs

If you want to really go the route of algorithms for heterogeneous sets, check https://www.boost.org/doc/libs/1_65_0/libs/hana/doc/html/group__group-Searchable.html#ga3a168950082f38afd9edf256f336c8ba

alfC
  • 14,261
  • 4
  • 67
  • 118