I have a reference to MyOjbect, but the the exact object depends on a condition. So I want to do something like this:
MyObject& ref;
if([co
What I like to do is a lambda that's immediately executed.
Let's suppose we want a const std::string& to a variable from under the map - if map does not contain given key - we want to throw.
int main()
{
std::map myMap = {{"key", "value"}};
const std::string& strRef = [&]()->const std::string& {
try {
return myMap.at("key"); // map::at might throw out_of_range
}
catch (...) {
// handle it somehow and/or rethrow.
}
}(); // <- here we immediately call just created lambda.
}
You could also use std::invoke() to make it more readable (since C++17)
int main()
{
std::map myMap = {{"key", "value"}};
const std::string& strRef = std::invoke([&]()->const std::string& {
try {
return myMap.at("key"); // map::at might throw out_of_range
}
catch (...) {
// handle it somehow and/or rethrow.
}
});
}