boost::可选和类型转换
boost::optional and type conversion
我想知道,当B
可以从A
构造时,是否有一种优雅的方法将boost::optional<A>
强制转换为boost::optional<B>
,尽管是明确的。这项工作:
# include <boost/optional.hpp>
class Foo
{
int i_;
public:
explicit Foo(int i) : i_(i) {}
};
int main()
{
boost::optional<int> i;
... // i gets initialized or not
boost::optional<Foo> foo;
foo = boost::optional<Foo>(bool(i), Foo(i.value_or(0 /*unused value*/)));
return 0;
}
但需要在其中加入一些永远不会被使用的价值似乎很尴尬。有更好的建议吗?
template<class T, class U>
boost::optional<T> optional_cast( U&& u ) {
if (u) return T(*std::forward<U>(u));
else return {};
}
也将有趣地使用指针。
int main() {
boost::optional<int> i;
... // i gets initialized or not
boost::optional<Foo> foo = optional_cast<Foo>(i);
return 0;
}
在C++03 中
template<class T, class U>
boost::optional<T> optional_cast( U const& u ) {
if (u) return T(*u);
else return boost::none;
}
将起作用,但在许多情况下效率较低。
相关文章:
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- C++中的双指针类型转换
- 逐位操作的隐式类型转换
- 模板中的类型转换
- 在 C++(和 C)中进行类型转换时明显不一致
- 字符类型转换不兼容
- 来自 Android 应用程序内部的 boost 类型的 boost::wrapexcept<boost::system::system_error> 的未捕获异常
- 将复杂的非基元C++数据类型转换为 Erlang/Elixir 格式,以使用 NIF 导出方法
- C++:用户定义的显式类型转换函数错误
- 将类指针类型转换为键时出错
- 通过引用传递参数时C++类型转换
- 操作方法:将 boost::endian 缓冲区类型转换回本机格式
- XLL由XLW制造,BOOST UBLAS MyMatrix数据类型转换为双**失败
- 混合类型的Boost运算符-转换和私有成员
- 将标量乘以boost.units.quantity(自动类型转换问题?)
- boost::可选和类型转换
- 转换boost::变体类型的std::vector
- 如何防止使用多种整数类型的boost::变体类型的隐式转换
- Boost Fusion:将适应的结构体类型转换为文本