gpt-3.5-turbo-0125· OpenAI
WildChat-4.8M (AI2)
Write C++ class analog for std::optional
- User
Write C++ class analog for std::optional
- Assistantcpp
#include <iostream> #include <exception> template <class T> class Optional { private: bool hasValue; T value; public: Optional() : hasValue(false) {} Optional(const T& value) : hasValue(true), value(value) {} T& operator*() { if (!hasValue) { throw std::exception("Trying to access value of empty optional"); } return value; } T* operator->() { if (!hasValue) { throw std::exception("Trying to access value of empty optional"); } return &value; } T value_or(const T& defaultValue) { return hasValue ? value : defaultValue; } bool has_value() { return hasValue; } void reset() { hasValue = false; } }; int main() { Optional<int> opt1; std::cout << "opt1 has value: " << opt1.has_value() << std::endl; Optional<int> opt2(10); std::cout << "opt2 has value: " << opt2.has_value() << std::endl; std::cout << "Value of opt2: " << *opt2 << std::endl; std::cout << "Value of opt1 with default: " << opt1.value_or(100) << std::endl; opt1.reset(); std::cout << "opt1 has value after reset: " << opt1.has_value() << std::endl; return 0; } - User
Есть класс User с полями login, first_name, family_name и patronymic. Последние 2 должны быть Optional. Реализуй это
- Assistantcpp