这就像是std::optional
,但不会存储额外的bool值。用户必须确保在初始化后才能访问。
template<class T>
union FakeOptional { //Could be a normal struct in which case will need std::aligned storage object.
FakeOptional(){} //Does not construct T
template<class... Args>
void emplace(Args&&... args){
new(&t) T{std::forward<Args&&>(args)...};
}
void reset(){
t.~T();
}
operator bool() const {
return true;
}
constexpr const T* operator->() const {
return std::launder(&t);
}
constexpr T* operator->() {
return std::launder(&t);
}
T t;
};
如果您想知道为什么我需要这样一个不常用的数据结构,请查看这里:https://gitlab.com/balki/linkedlist/tree/master 问题:
- 可以忽略
std::launder
吗?我认为不行。 - 由于
std::launder
仅在c++17中可用,如何在c++14中实现上述类?boost::optional
和std::experimental::optional
是否需要类似的功能,或者它们使用了编译器特定的技术?
注意:很容易忽略,该类型被声明为 union
。这意味着真正没有调用 T
的构造函数。参考链接:https://gcc.godbolt.org/z/EVpfSN
operator bool() const { return true; }
...FakeOptional
。没错,听起来很对。 - Barryunion FakeOptional
- balki__builtin_launder
或者类似的东西。 - Passer Bylaunder
吗?constexpr T* operator->() {return &t;}
- balki