Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstdio>
- #include <iostream>
- #include <string>
- enum class file_open_error
- {
- file_not_found,
- other
- };
- namespace whatever
- {
- template <class E>
- class unexpected
- {
- public:
- constexpr unexpected(const E& value)
- {
- val = value;
- }
- constexpr const E& value() const&
- {
- return val;
- }
- private:
- E val;
- };
- template <class T, class E>
- class expected
- {
- public:
- typedef T value_type;
- typedef E error_type;
- typedef unexpected<E> unexpected_type;
- constexpr expected(const value_type& value)
- {
- this->val = value;
- this->has_val = true;
- }
- constexpr expected(const unexpected_type& value)
- {
- this->unexpect = value;
- this->has_val = false;
- }
- constexpr operator bool() const noexcept
- {
- return has_val;
- }
- constexpr const T& operator *() const&
- {
- return val;
- }
- constexpr const E& error() const&
- {
- return unexpect.value();
- }
- private:
- bool has_val;
- union
- {
- value_type val;
- unexpected_type unexpect;
- };
- };
- }
- whatever::expected<FILE*, file_open_error> open_file(std::string pathToFile)
- {
- #pragma warning(suppress : 4996)
- FILE* file = fopen(pathToFile.c_str(), "r");
- if (file)
- {
- return file;
- }
- else
- {
- switch (errno)
- {
- case ENOENT:
- return whatever::unexpected<file_open_error>(file_open_error::file_not_found);
- default:
- return whatever::unexpected<file_open_error>(file_open_error::other);
- }
- }
- }
- int main()
- {
- whatever::expected<FILE*, file_open_error> file = open_file("C:/test.dat");
- if (file)
- {
- std::cout << "File opened successfully!\n";
- fclose(*file);
- }
- else
- {
- switch (file.error())
- {
- case file_open_error::file_not_found:
- std::cout << "File not found!\n";
- break;
- default:
- std::cout << "Other error!\n";
- break;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement