boost ::可选和类型转换

P-G*_*-Gn 5 c++ boost boost-optional

我在想,如果有蒙上了一种优雅的方式boost::optional<A>到boost::optional<B>时B可以从构造A,虽然明确地.这有效:

# 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;
}
Run Code Online (Sandbox Code Playgroud)

但需要放入一些永远不会被使用的价值似乎很尴尬.还有更好的建议吗?

Yak*_*ont 8

template<class T, class U>
boost::optional<T> optional_cast( U&& u ) {
  if (u) return T(*std::forward<U>(u));
  else return {};
}
Run Code Online (Sandbox Code Playgroud)

将有趣地使用指针.

int main() {
  boost::optional<int> i;
  ... // i gets initialized or not
  boost::optional<Foo> foo = optional_cast<Foo>(i);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

在C++ 03中

template<class T, class U>
boost::optional<T> optional_cast( U const& u ) {
  if (u) return T(*u);
  else return boost::none;
}
Run Code Online (Sandbox Code Playgroud)

相反,但在许多情况下效率较低.