【发布时间】:2018-03-22 23:06:03
【问题描述】:
这不起作用:
struct Type {
virtual bool func(const std::string& val) const noexcept = 0;
}
// in main
optional<Type> = some_function_returning_optional_type();
失败并显示错误消息:
error: cannot declare field 'std::experimental::fundamentals_v1::_Optional_base<Type, false>::<anonymous union>::_M_payload' to be of abstract type 'Type'
将Type 更改为具有非纯函数有效,但在这种情况下不合适,因为在我的代码中不能有Type 的实例,只有从它继承的类应该能够存在.
【问题讨论】:
-
如何实例化抽象类型以放入可选项中?如果您实际上是在实例化一个具体类型,但使用指向抽象类型的指针,那么您可以将一个指针(或智能指针)放入您的可选项中。但是请注意,如果
nullptr不够用,您只需要一个可选的,并且您需要处理即使nullptr也无法创建的特殊情况。
标签: c++ templates virtual abstract optional