英文:
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<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++?
答案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&...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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论