gpt4 book ai didi

c++ - 如何实现 std::optional 的拷贝构造函数?

转载 作者:行者123 更新时间:2023-11-28 02:59:13 25 4
gpt4 key购买 nike

我正在实现 std::optional ,但遇到了其中一个障碍 copy constructors .

这是我的实现草图:

#include <type_traits>

template<typename T>
class optional
{
public:
constexpr optional()
: m_is_engaged(false)
{}

constexpr optional(const optional &other)
: m_is_engaged(false)
{
operator=(other);
}

constexpr optional &operator=(const optional &other)
{
if(other.m_is_engaged)
{
return operator=(*other);
}
else if(m_is_engaged)
{
// destroy the contained object
(**this).~T();
m_is_engaged = false;
}

return *this;
}

template<typename U>
optional &operator=(U &&value)
{
if(m_is_engaged)
{
operator*() = value;
}
else
{
new(operator->()) T(value);
m_is_engaged = true;
}

return *this;
}

T* operator->()
{
return reinterpret_cast<T*>(&m_data);
}

T &operator*()
{
return *operator->();
}

private:
bool m_is_engaged;
typename std::aligned_storage<sizeof(T),alignof(T)>::type m_data;
};

#include <tuple>

int main()
{
optional<std::tuple<float, float, float>> opt;

opt = std::make_tuple(1.f, 2.f, 3.f);

return 0;
}

问题是编译器提示 optionalconstexpr 构造函数没有空体:

$ g++ -std=c++11 test.cpp 
test.cpp: In copy constructor ‘constexpr optional<T>::optional(const optional<T>&)’:
test.cpp:15:5: error: constexpr constructor does not have empty body
}
^

否则我不确定如何初始化optional::m_data,而且我无法在网络上找到引用实现(boost::optional显然不使用 constexpr)。

有什么建议吗?

最佳答案

在 C++11 中,标记为 constexpr 的函数和构造函数的功能非常有限。对于构造函数,它基本上不能包含除static_asserttypedefusing 声明using 指令 以外的任何内容, 这排除了在构造函数体内调用 operator= 的可能性。

关于c++ - 如何实现 std::optional 的拷贝构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21248347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com