Edit:
So, this question has been misinterpreted to such a ridiculous degree that it no longer makes sense. I donโt know how, since the question I really asked was whether my specific implementation of this โyesโ was known to be pointless, yes, not remotely resembling the C ++ idiomatic macro and - is it necessary use auto , or if there was a suitable workaround. He should not have paid much attention to this, and, of course, there was no such misunderstanding on such a scale. It makes no sense to ask the respondents to edit their answers, I donโt want someone to lose their reputation on this issue, and there is some good information for potential potential viewers, so Iโm going to arbitrarily choose one of the below voted answers to evenly distribute the reputation involved. Move on, nothing is visible here.
I saw this question and decided it would be interesting to write a with statement in C ++. The auto keyword makes this very easy, but is there a better way to do this, perhaps without using auto ? For brevity, I have reduced some bits of code a bit.
template<class T> struct with_helper { with_helper(T& v) : value(v), alive(true) {} T* operator->() { return &value; } T& operator*() { return value; } T& value; bool alive; }; template<class T> struct with_helper<const T> { ... }; template<class T> with_helper<T> make_with_helper(T& value) { ... } template<class T> with_helper<const T> make_with_helper(const T& value) { ... } #define with(value) \ for (auto o = make_with_helper(value); o.alive; o.alive = false)
Here is an example (updated) of use with a more typical case, which shows the use of with , as it is found in other languages.
int main(int argc, char** argv) { Object object; with (object) { o->member = 0; o->method(1); o->method(2); o->method(3); } with (object.get_property("foo").perform_task(1, 2, 3).result()) { std::cout << (*o)[0] << '\n' << (*o)[1] << '\n' << (*o)[2] << '\n'; } return 0; }
I chose o because it is an unusual identifier, and its form gives the impression of a โcommon thing." If you have an idea for a better identifier or more usable syntax, please suggest it.