vendredi 29 janvier 2021

Range based for loop through non-const literal c++

Compiler context: I am compiling with GDB v8.3 Ubuntu with options g++ -Im -O2 -std=c++0x.

Very frequently I need to complete some loop for two or three objects so I use wrap the expression in a range based for loop with a containing litteral.

In Python3 this would look like:

a = [1,2,3]
b = [4,5,6]

for v in (a,b):
    func(v)

In c++ this obviously isn't so simple. As far as I am aware, using {a,b} creates some type of initializer list, therefor casting does not properly work. In my attempts I come to something of this sort, but do no understand how I would properly pass by reference and also have it be mutable, as my compiler complains this is neccessarily const.

vector<int> a {1,2,3};
vector<int> b {4,5,6};

for(auto& v: {a,b}) // error non-const
    func(v);

Aucun commentaire:

Enregistrer un commentaire