I am playing with C++23 std::optional
additions, but I can not figure out how to elegantly access the value of object if optional
is active.
I know I can use if
, but that is so C++20.
I really like C++23 API changes, but I can not figure out how to skip the boilerplate of implementing identity. For example:
#include <functional>
#include <iostream>
#include <optional>
void print(std::optional<std::string>& name) {
name.transform([](std::string& x) {
std::cout << x << std::endl;
// I just want to print, without modifying optional, but next line is required
return x;
});
}
int main() {
std::optional<std::string> name{{"Bjarne"}};
print(name);
}
It almost feels like std::optional
is missing invoke
member function.
note: in my example I do not chain anything else after transform, but that is for brevity, I care about optional not being modified.