C++纯函数式库中Option Monad取值方案设计与代码问题咨询
C++纯函数式库Option Monad的设计问题与实现疑问
我正在开发一款C++纯函数式库,在实现Option Monad时遇到设计问题。以下是我的实现代码:
namespace ns { struct _NoValue_t {}; const _NoValue_t _NoValue; template<typename T> class Option { bool _has_value; std::unique_ptr<T> _value; Option(const T& value) : _has_value(true), _value(new T(value)) {} Option(T&& value) : _has_value(true), _value(new T(std::move(value))) {} Option(const _NoValue_t&) : _has_value(false), _value(nullptr) {}; public: Option(Option<T>&& other) : _has_value(other._has_value), _value(other._value) { _has_value = false; } const Option<T>& operator=(Option<T>&& other) { _has_value = other._has_value; _value = std::move(other._value); other._value = nullptr; other._has_value = false; return *this; } bool has_value() const { return _has_value; }; const T& value_else(const T& t) const { return _has_value?(*_value):t; } static Option<T> some(const T& value) { return Option<T>(value); } static Option<T> some(T&& value) { return Option<T>(std::move(value)); } static Option<T> none() { return Option<T>(_NoValue); } }; //class Option }
当前仅能通过value_else方法取值,但当用户无合适默认值时,创建默认值的成本可能很高。我调研了Kotlin、Scala等混编OOP与FP的语言的函数式错误处理方案,列出以下候选解决思路:
- 思路1:无值时抛出异常(类似
std::optional),但为保持纯函数式风格希望忽略该方案
const T& value() const { if(!this->_has_value) throw no_such_value_exception("if !option.has_value must not retrieve value"); return *_value; }
- 思路2:传入生成默认值的函数以避免不必要的对象创建,但无法返回引用(若有实现方法请告知)
template<typename Generator> T get(Generator&& generator) const { if(!this->_has_value) return generator(); else return *this->_value; }
- 思路3:无值时返回默认构造对象,但部分类型无默认构造函数,且存在与方案2相同的问题
T get() const { if(!this->_has_value) return T(); else return *this->_value; }
- 思路4:提供
unsafe_get方法明确标识危险性
const T& get() const { return *this->_value; }
想请教两个问题:
- 我的实现代码中是否存在不安全逻辑、错误或其他潜在问题?
- 我是否过度担忧了库使用者的失误?
内容的提问来源于stack exchange,提问作者linus
相关产品推荐
相关产品推荐

