如何划分boost :: optional <double>?

jav*_*red 3 c++ boost boost-optional

我有这样的代码:

boost::optional<double> result = _ind1.Value() / _ind2.Value();
Run Code Online (Sandbox Code Playgroud)

每个arg boost::optional<double>也是:

boost::optional<double> Value() {
    return value;
}
Run Code Online (Sandbox Code Playgroud)

错误是:

Error 1 error C2676: binary '/' : 'boost::optional<T>' does not define this operator or a conversion to a type acceptable to the predefined operator 2 IntelliSense: no operator "/" matches these operands operand types are: boost::optional<double> / boost::optional<double>

我明白分裂似乎没有定义.我希望结果是boost::none两个参数中的任何一个none- 否则我希望它是正常的双重除法.我应该自己写吗?

Zan*_*ynx 11

当然,支持诸如双倍分割之类的简单操作.

但你并不想分开双打.你试图划分boost::optional<double>s,这是一个完全不同的故事.

如果需要,可以为此定义除法运算符.它可能看起来像(未经测试):

template<typename T>
boost::optional<T> operator/(const boost::optional<T>& a, const boost::optional<T>& b)
{
    if(a && b) return *a / *b;
    else return boost::optional<T>();
}
Run Code Online (Sandbox Code Playgroud)

在C++ 11中(代码由Yakk提供):

template<class T,class U> struct divide_result {
  typedef typename std::decay<decltype(std::declval<T>()/std::declval<U>())>::type;
};
template<class T, class U> using divide_result_t=typename divide_result<T,U>::type;
template<typename T,typename U>
boost::optional<divide_result_t<T,U>> operator/(const boost::optional<T>& a, const boost::optional<U>& b)
{
    if(a && b) return *a / *b;
    else return boost::none;
}
Run Code Online (Sandbox Code Playgroud)

我使用了一个模板,因为现在它对int,float等也有好处.