Pattern
if(auto var(...);
condition
)
/* do something */
;
switch(auto var(...); var) {
/* do something */
}
Description
When we want to find a key in std::map
, we have to make iterator to store result of find()
. Then we use if
statement to know iterator found what we want or not(iterator != map.end()
). This iterator is used only once for the statement. It is wastage and annoying that the iterator is never used after the statement, while intellisense keeps to display the iterator.
In C++17, if
and switch
statement can have initializer
, like for
statement. After statement is done, the initialized variable is not accessible anymore. This is helpful which our code keeps tidy and makes easier to refactor.
Example
std::map<int, std::string> nameMap;
if (auto itr(nameMap.find(2)); itr != nameMap.end())
std::cout << itr->first << ": " << itr->second.c_str() << std::endl;
//itr lifespan is over after this line.
I believe this feature is built taking the idea from Go.
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit