Opcioni tip

Napisati klasu optional koja predstavlja opcioni tip podatka. Implementirati:

template <typename T>
class optional {
public:
    optional();
    optional(const T &value);
    bool is_present() const;
    T& value();
    const T& value() const;
	void emplace(const T &value);
};

Test

#include <iostream>

namespace matf {

    // Ovde ide vasa implementacija

} // namespace matf

int main(void)
{
	matf::optional<int> opt1; // empty optional
	if (!opt1.is_present()) {
		std::cout << "opt1 is empty" << std::endl;
	}

	matf::optional<int> opt2(42); // optional with value
	if (opt2.is_present()) {
		std::cout << "opt2 has value: " << opt2.value() << std::endl;
	}

	return 0;
}

Rešenje

main.cpp

#include <iostream>
#include <stdexcept>

namespace matf {

	template <typename T>
	class optional {
		public:
			optional() : has_value(false) {}
			optional(const T &value) : has_value(true), storage(value) {}

			bool is_present() const {
				return has_value;
			}

			T& value() {
				if (!has_value) {
					throw std::runtime_error("No value present");
				}
				return storage;
			}

			const T& value() const {
				if (!has_value) {
					throw std::runtime_error("No value present");
				}
				return storage;
			}

			void reset() {
				has_value = false;
			}

			void emplace(const T &value) {
				storage = value;
				has_value = true;
			}

		private:
			bool 	has_value;
			T 		storage;
	};

} // namespace matf

int main(void)
{
	matf::optional<int> opt1; // empty optional
	if (!opt1.is_present()) {
		std::cout << "opt1 is empty" << std::endl;
	}

	matf::optional<int> opt2(42); // optional with value
	if (opt2.is_present()) {
		std::cout << "opt2 has value: " << opt2.value() << std::endl;
	}

	return 0;
}