if (auto itr (character_map.find(c)); itr != character_map.end()) {
// *itr is valid. Do something with it.
} else {
// itr is the end-iterator. Don't dereference.
}
// itr is not available here at all
switch (char c (getchar()); c) {
case 'a': move_left(); break;
case 's': move_back(); break;
case 'w': move_fwd(); break;
case 'd': move_right(); break;
case 'q': quit_game(); break;
case '0'...'9': select_tool('0' - c); break;
default:
std::cout << "invalid input: " << c << '\n';
}
How it works...
带有初始化的if和switch相当于语法糖一样。
// if: before C++17
{
auto var(init_value);
if (condition){
// branch A. var is accessible
} else {
// branch B. var is accessible
}
// var is still accessible
}
// if: since C++17
if (auto var (init_value); condition){
// branch A. var is accessible
} else {
// branch B. var is accessible
}
// var is not accessible any longer
// switch: before C++17
{
auto var (init_value);
switch (var) {
case 1: ...
case 2: ...
...
}
// var is still accessible
}
// switch: since C++17
switch(auto var (init_value); var){
case 1: ...
case 2: ...
...
}
// var is not accessible any longer
if (auto shared_pointer (weak_pointer.lock()); shared_pointer != nullptr) {
// Yes, the shared object does still exist
} else {
// shared_pointer var is accessible, but a null pointer
}
// shared_pointer is not accessible any longer