迭代不同类型 [英] Iterating over different types
本文介绍了迭代不同类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出以下代码:
struct Window{
void show();
//stuff
}w1, w2, w3;
struct Widget{
void show();
//stuff
}w4, w5, w6;
struct Toolbar{
void show();
//stuff
}t1, t2, t3;
我想要显示
:
for (auto &obj : {w3, w4, w5, t1})
obj.show();
但是这不会编译,因为 std :: initializer_list< T& / code>中的
中找不到
T
,事实上没有真正的 T
。我不想创建类型擦除类型,因为所需的代码量和不必要的运行时开销。我如何正确地写我的循环,使得 obj
的类型分别推导到概念列表中的每个项目?
However this does not compile since the std::initializer_list<T>
in the for
-loop cannot deduce T
and in fact there is not really a T
that would fit. I don't want to create a type erasure type because of the amount of code required and the unnecessary runtime overhead. How do I correctly write my loop so that the type of obj
is deduced for every item in the conceptual list separately?
推荐答案
在现代C ++中,您可以使用折叠表达式,通过应用成员函数遍历异质参数:
In modern C++ you'd use fold expressions, to "walk through" your heterogenous arguments applying the member function:
auto Printer = [](auto&&... args) {
(args.show(), ...);
};
Printer(w1, w2, w3, w4, w5, w6, t1, t2, t3);
这篇关于迭代不同类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文