Initializer list in a range for loop(循环范围内的初始化列表)
问题描述
我有从单个超类型派生的不同类型的对象.我想知道在这样的循环范围内使用 std::initializer
列表是否有任何缺点:
I have objects of different types derived from a single super-type. I wonder if there are any disadvantages in using std::initializer
list in a range for loop like this:
for(auto object: std::initializer_list<Object *>{object1, object2, object3}) {
}
是否完全可以且高效,还是使用数组更好?对我来说,std::array
解决方案似乎对编译器的限制更大,并且显式说明大小有一个缺点:
Is it completely OK and efficient or would it be better to use an array? To me the std::array
solution seems to be more restrictive for the compiler and there is a disadvantage of explicitly stating the size:
for(auto object: std::array<Object*, 3>{object1, object2, object3}) {
}
是否有任何其他或更好的方法来迭代明确给定的对象列表?
Is there any other or nicer way of iterating over an explicitly given list of objects?
推荐答案
循环内部不需要使用冗长的std::initializer_list
There is no need to use the verbose std::initializer_list
inside the loop
#include <iostream>
#include <initializer_list>
struct B { virtual int fun() { return 0; } };
struct D1 : B { int fun() { return 1; } };
struct D2 : B { int fun() { return 2; } };
int main()
{
D1 x;
D2 y;
B* px = &x;
B* py = &y;
for (auto& e : { px, py })
std::cout << e->fun() << "
";
}
实例.
如果您想在不定义 px
和 py
的情况下即时执行此操作,您确实可以使用 std::initializer_list<B*>{ &x, &y }
在循环内.
If you want to do it on-the-fly without defining px
and py
, you can indeed use std::initializer_list<B*>{ &x, &y }
inside the loop.
这篇关于循环范围内的初始化列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:循环范围内的初始化列表
基础教程推荐
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 设计字符串本地化的最佳方法 2022-01-01