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在我的代码中不能有 的实例,只有从它继承的类才能存在。
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设计上没有任何间接性。
| 归档时间: |
|
| 查看次数: |
986 次 |
| 最近记录: |