为什么我不能有 std::optional<T> 其中 T 是抽象的?

mus*_*tze 2 c++ virtual templates abstract optional

这不起作用:

struct Type {
    virtual bool func(const std::string& val) const noexcept = 0;
}

// in main
optional<Type> = some_function_returning_optional_type();
Run Code Online (Sandbox Code Playgroud)

并失败并显示错误消息:

error: cannot declare field 'std::experimental::fundamentals_v1::_Optional_base<Type, false>::<anonymous union>::_M_payload' to be of abstract type 'Type'
Run Code Online (Sandbox Code Playgroud)

将 更改Type为具有非纯函数有效,但在这种情况下不合适,因为Type在我的代码中不能有 的实例,只有从它继承的类才能存在。

Vit*_*meo 5

std::optional<T>就地存储它的值 - 因此它需要知道 的大小T才能正常工作,并且T必须是可以实例化的具体类型。你可以认为std::optional<T>是:

template <typename T>
struct optional
{
    std::aligned_storage_t<sizeof(T), alignof(T)> _data;
    bool _set;
};
Run Code Online (Sandbox Code Playgroud)

抽象类型代表一个接口 - 需要多态性和某种间接性才能使用抽象类型。std::optional设计上没有任何间接性。

  • @musicmatze:你可以有一个 `std::optional&lt;std::unique_ptr&lt;Type&gt;&gt;`。但是为什么不使用 `std::unique_ptr&lt;Type&gt;` 呢? (5认同)
  • @musicmatze 一个指针隐式可以为空,它代表一个无效的返回值 (4认同)