I'm aware of declaring and initializing two different variables in a for loop with a std::pair
or an anonymous struct
type, but these do not work for my purposes.
Let's say I have the following class definition
class Object {
private:
int i;
public:
Object(int i) : i(i) { }
// everything else deleted
Object() = delete;
Object(const Object &) = delete;
Object(Object &&) = delete;
Object & operator=(const Object &) = delete;
Object & operator=(Object &&) = delete;
};
Is there any way I can initialize an Object
and an int
in the for
loop line. I don't want to add an extra block around the for loop or anything like that. I am okay with std::tuple
, std::pair
, anonymous structs
, whatever, just so long as it has the form
for(/* creates Object and int*/ ; /*whatever*/; /*whatever*/) { /* ... */}
or (if the syntax existed)
for( Object o(69), int i = 0; i < 10; ++i) { /* ... */ }
What I do not want is an extra named class definition. I have come up with this already:
for(class Container : private Object {
public:
int value;
Container(int i) : Object(i), value(0) { }
} container(69); /* ... */ ;
container.value < 10;
++container.value) { /* ... */}
But the class name Container
then becomes visible inside of the for loop, which I am trying to avoid.
My actual use of this is a std::lock_guard<std::mutex>
and a bool
, so that the mutex is released after exiting the loop.