可以在异构集合上使用 std::all_of(或更好地说,std::ranges::all_of)吗?

huangapple go评论66阅读模式
英文:

Can I use std::all_of (or better, std::ranges::all_of) over a heterogeneous collection?

问题

以下是翻译好的部分:

我有一些依赖于已初始化的各种`std::shared_ptr`值的代码。在其中一个或多个这些值尚未初始化的情况下,我希望只是从函数中返回。我想要的是这样的东西:

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); } ))
    {
        // 记录无法运行的情况
        return;
    }
    // 执行foo操作
}

这受到了我使用Python时的启发,在Python中编写这样的代码非常简单:

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

C++并没有像Python一样的异构容器,但它通过初始化器列表伪装得相当不错。在现代C++中,是否有一种表达这种面向对象泛化的方式呢?

英文:

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&lt;A&gt; myA;
std::shared_ptr&lt;B&gt; myB;
std::shared_ptr&lt;C&gt; myC;

void foo()
{
    if (not std::ranges::all_of( {myA, myB, myC}, [](auto&amp;&amp; x) { return bool(x); } ))
    {
        // log that this can&#39;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++?

答案1

得分: 2

您正在寻找通用(可变参数)解决方案:

if (not std::apply([](auto&...es) { return (es && ...); }, std::tie(myA, myB, myC))) {
    // 记录无法运行的情况
    return;
}

当然,如果您有这三个对象的明确引用,最好使用以下方式进行检查:

if (not (myA && myB && myC)) {

如果您想真正采用用于异构集合的算法路径,请查看 https://www.boost.org/doc/libs/1_65_0/libs/hana/doc/html/group__group-Searchable.html#ga3a168950082f38afd9edf256f336c8ba

英文:

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

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

of course, if you have the 3 objects explicitly, it is better to do if(not(myA &amp;&amp; myB &amp;&amp; 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

huangapple
  • 本文由 发表于 2023年6月22日 08:25:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76527925.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定