boost::可选和类型转换

boost::optional and type conversion

本文关键字:类型转换 boost      更新时间:2023-10-16

我想知道,当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;
}

将起作用,但在许多情况下效率较低。