Skip to content

Instantly share code, notes, and snippets.

@artivis
Last active May 6, 2018 12:58
Show Gist options
  • Save artivis/276eb793171d7d62fc47bbf2c910e5d7 to your computer and use it in GitHub Desktop.
Save artivis/276eb793171d7d62fc47bbf2c910e5d7 to your computer and use it in GitHub Desktop.
[cpp17] work-around std::optional<T&>
#include <functional>
#include <iostream>
#include <optional>
struct Foo
{
void read(const std::optional<std::reference_wrapper<std::string>>& text)
{
if (text)
std::cout << (*text).get() << "\n";
else
std::cout << "There is no text to read !\n";
(*text).get() = "Once upon a time...";
}
};
int main()
{
Foo foo;
std::string text("Hello world");
foo.read(std::reference_wrapper<std::string>(text));
std::cout << text << "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment