如何将范围存储为类中的字段? [英] How to store a range as a field in a class?
问题描述
我想将范围存储为类中的字段,以便以后可以重用几次.但是,与局部变量不同,我不能简单地将其类型指定为auto
.另一方面,库创建的范围类型非常复杂.我要花大量的时间才能手动找出正确的类型,而且如果我选择更改范围的获取方式,将来将很难维护.
I would like to store a range as a field in a class, so that I could reuse it several times later on. However, unlike local variables, I cannot simply specify it type as auto
. On the other hand, the types of ranges that the library creates are very complex. It would take me disproportionately long time to figure out the correct type by hand + it would be unmaintainable in the future if I would choose to change how the range is obtained.
所以,我想,也许我可以使用decltype
来帮助自己:
So, I thought, maybe I could use decltype
to help myself:
class MyClass {
public:
using MyRange = decltype(std::declval<std::vector<int*>>() | ranges::v3::view::filter([=](int* elem) { return true; }));
MyRange range;
}
(注意:我实际的std::declval
实际上更复杂,但是我想使示例简短.)
(note: my actual std::declval
is actually more complex, but I wanted to make the example brief.)
但是我得到一个错误:
a lambda cannot appear in an unevaluated context
But I get an error:
a lambda cannot appear in an unevaluated context
所以,我的问题是:
- 如何避免使用lambda并使我的
decltype
工作? - 或者也许有一种更好/更干净的方法来获取范围的类型,以将其声明为类中的字段?
- How can I avoid using the lambda and get my
decltype
working? - Or maybe there is a better/cleaner way to get a type of a range in order to declare it as a field in a class?
推荐答案
此处的语言很有帮助:如果decltype
中允许使用lambda,则它对您无济于事,因为您将无法产生除默认初始化之外的类型为MyRange
的值.由于最常见的lambda表达式具有唯一的类型,因此您无法生成正确类型的函数对象以传递给view::filter
以使其返回可存储在MyRange
中的内容.
The language is being helpful here: if the lambda were allowed in decltype
, it wouldn't help you, because there would be no way for you to produce a value of type MyRange
other than via default-initialization. Since very occurrence of a lambda expression has a unique type, you couldn't produce a function object of the correct type to pass to view::filter
to get it to return something you could store in a MyRange
.
解决方法是不要那样做";例如,将函数对象存储在某处,并在decltype
中引用它.在C ++ 17中,例如 :
The workaround is to "don't do that"; e.g., store your function object somewhere and refer to it in the decltype
. In C++17, for example:
struct MyClass {
static constexpr auto pred = [](int* elem) { return true; };
using MyRange = decltype(std::declval<std::vector<int*>&>() | ranges::v3::view::filter(pred));
MyRange range;
};
请注意使用std::vector&
.如显式range-v3十进制类型评估为无效吗?
这篇关于如何将范围存储为类中的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!