Skip to content

Instantly share code, notes, and snippets.

@Bktero
Last active November 20, 2017 21:08
Show Gist options
  • Save Bktero/7be3aa49236e64388f15bddf7c2e3534 to your computer and use it in GitHub Desktop.
Save Bktero/7be3aa49236e64388f15bddf7c2e3534 to your computer and use it in GitHub Desktop.
[C++17] Example of std::optional
#include <iostream>
#include <optional>
class Image
{
public:
Image(const std::string& path) : path(path)
{}
std::string getPath()
{
return path;
}
private:
std::string path;
};
std::optional<Image> load_image(const std::string& path)
{
if (path == "the_image.png")
{
return path;
}
else
{
return std::nullopt;
}
}
void try_to_load(const std::string& path)
{
if (auto image = load_image(path))
{
std::cout << "Image loaded: " << image.value().getPath() << std::endl;
}
else
{
std::cout << "Image not found" << std::endl;
}
}
int main()
{
try_to_load("the_image.png");
try_to_load("another_image.png");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment