Last active
November 20, 2017 21:08
-
-
Save Bktero/7be3aa49236e64388f15bddf7c2e3534 to your computer and use it in GitHub Desktop.
[C++17] Example of std::optional
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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