It does not work because in {a,b}
you are making a copy of a
and b
. One possible solution would be to make the loop variable a pointer, taking the addresses of a
and b
:
#include <initializer_list>
struct Obj {
int i;
};
Obj a, b;
int main() {
for(auto obj : {&a, &b}) {
obj->i = 123;
}
}
See it live
Note: it is generically better to use auto
, as it could avoid silent implicit conversions
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…