ARTICLE AD BOX
Designated initializers, added in C++20, allow us to name the arguments passed to the initializer list, making the code easier to understand.
Commented out is the syntax I would like to use in this case. Using .headers = {{"Set-Cookie", "12345678"}} only works when the headers member is not of an std::optional<X> type, but is purely the unordered_map. Here I need to initialize optional values before passing them into the initializer, otherwise the code won't compile.
#include <iostream> #include <optional> #include <unordered_map> struct HttpResponse { int status; std::optional<std::unordered_map<std::string, std::string>> headers; }; HttpResponse myFunc(bool success) { if (success) { std::unordered_map<std::string, std::string> headers_to_return = {{"Set-Cookie", "12345678"}}; return HttpResponse{ .status = 200, .headers = headers_to_return // Nicer syntax // .headers = {{"Set-Cookie", "12345678"}} }; } else { return HttpResponse{ .status = 403 }; } } int main() { HttpResponse res = myFunc(true); if (res.headers) { for (auto& header_pair : res.headers.value()) std::cout << header_pair.first << ": " << header_pair.second << std::endl; } return 0; }A solution, if one exists, can use a standard newer than C++20
