Implementing boost::optional in c++11

﹥>﹥吖頭↗ 提交于 2019-11-30 14:04:42

To make this work with references you definitely need an explicit specialization, because you can't do placement new of a reference: you need to use pointers for storage.

Beyond that, the code is missing a copy assignment operator. A move constructor, and move assignment operator would also be nice (especially since that's the #1 reason to reimplement boost::optional: the one in boost is lacking them).

The optional types were proposed for C++14 but due to some corner cases around behavior undefined in standards it got postponed to C++17.

Fortunately, the UB issue shouldn't matter to most people because all major compilers do define it correctly. So unless you are using old compilers, you can actually just drop in the code available to implement optional type in your project (it's just one header file):

https://raw.githubusercontent.com/akrzemi1/Optional/master/optional.hpp

Then you can use it like this:

#if (defined __cplusplus) && (__cplusplus >= 201700L)
#include <optional>
#else
#include "optional.hpp"
#endif

#include <iostream>

#if (defined __cplusplus) && (__cplusplus >= 201700L)
using std::optional;
#else
using std::experimental::optional;
#endif

int main()
{
    optional<int> o1,      // empty
                  o2 = 1,  // init from rvalue
                  o3 = o2; // copy-constructor

    if (!o1) {
        cout << "o1 has no value";
    } 

    std::cout << *o2 << ' ' << *o3 << ' ' << *o4 << '\n';
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!