表示 an 的“明显”方式std::optional<T>
是使用指示值是否与union
包含 a 的 a一起设置T
,即,如下所示:
template <typename T>
class optional {
bool isSet = false;
union { T value; };
public:
// ...
};
默认情况下, 中的成员union
未初始化。相反,您需要使用放置new
和手动销毁来管理union
. 从概念上讲,这类似于使用字节数组,但编译器会处理任何对齐要求。
这是一个显示一些操作的程序:
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <cassert>
template <typename T>
class optional {
bool isSet = false;
union { T value; };
void destroy() { if (this->isSet) { this->isSet = true; this->value.~T(); } }
public:
optional() {}
~optional() { this->destroy(); }
optional& operator=(T&& v) {
this->destroy();
new(&this->value) T(std::move(v));
this->isSet = true;
return *this;
}
explicit operator bool() const { return this->isSet; }
T& operator*() { assert(this->isSet); return this->value; }
T const& operator*() const { assert(this->isSet); return this->value; }
};
int main()
{
optional<std::string> o, p;
o = "hello";
if (o) {
std::cout << "optional='" << *o << "'\n";
}
}