Initializer list in a range for loop

后端 未结 2 1036
春和景丽
春和景丽 2021-02-05 15:54

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

2条回答
  •  孤城傲影
    2021-02-05 16:23

    There is no need to use the verbose std::initializer_list inside the loop

    #include 
    #include 
    
    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() << "\n";    
    }
    

    Live Example.

    If you want to do it on-the-fly without defining px and py, you can indeed use std::initializer_list{ &x, &y } inside the loop.

提交回复
热议问题