How do I write complex initialization?--Stack Overflow
Quick A: Initialize it using a lambda that’s invoked immediately.
Recently on SO:
Best practice for declaring variable without initialising it, so auto is unavailable
I want to declare two variables of the same type, and have the compiler figure out the types. However I don't want to initialise one of the variables until later. I don't think I can use
autohere, so what's the best option?std::vector<int> v; // `start` and `end` should be the same type auto start = v.begin(); ??? end; // complicated code to assign a value to `end` (i.e. putting // the code in a function or using ?: is not practical here) if (...) { end = ...; } else { end = v.end(); }What's the best way to tell the compiler that
endshould be the same type asstart, but without having to initialise the variable?auto start = v.begin(), end; // Doesn't work, `end` has to be initialised decltype(start) end; // Does work, but not sure if it's best practiceUpdate
A couple of comments have suggested ways that would work in certain situations, so I am clarifying my situation here:
std::vector<int> v; int amount = 123; // `start` and `end` should be the same type auto start = v.begin(); ??? end; // code to assign a value to `end` if (amount) { end = start + amount; amount = 0; } else { end = v.end(); }I believe a lamda function would be trickier here, because
amountis being reset to0afterendis calculated, so in a lamda function that calculates a value forend,amount = 0would have to come after thereturnstatement. The only option would be to create more local variables, which would incur an (admittedly tiny) performance penalty.

While we wait for CppCon 2015 in September, we’re featuring videos of some of the 100+ talks from CppCon 2014. Here is today’s feature:
There was a lot of interest for the
A new article of interest for library developers:
While we wait for CppCon 2015 in September, we’re featuring videos of some of the 100+ talks from CppCon 2014. Here is today’s feature: