Skip to content

Instantly share code, notes, and snippets.

@ntauth
Last active July 9, 2018 15:34
Show Gist options
  • Save ntauth/a00efe136d4455a8db2cf0dc2991bd63 to your computer and use it in GitHub Desktop.
Save ntauth/a00efe136d4455a8db2cf0dc2991bd63 to your computer and use it in GitHub Desktop.
Semantic C++: Optionals
/**
* @author Ayoub Chouak (@ntauth)
* @website http://chouak.me
* @note This requires a C++17-compliant compiler (ex. MSVC14, Clang5)
*/
#include <optional>
#include <iostream>
#include <string>
#include <chrono>
template <typename U>
std::ostream& operator<<(std::ostream& os, std::optional<U> nullable) {
if (nullable.has_value())
os << nullable.value();
return os;
}
int main(int argc, char** argv)
{
std::optional<int> int_n;
std::optional<std::string> string_n;
std::optional<std::string> string_n_{ "I have a value!" };
std::cout << int_n << string_n << string_n_ << std::endl;
std::cin.get();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment