how to divide boost::optional<double>?

烈酒焚心 提交于 2019-12-10 20:41:26

问题


I have such code:

boost::optional<double> result = _ind1.Value() / _ind2.Value();

Each arg is boost::optional<double> too:

boost::optional<double> Value() {
    return value;
}

Errors are:

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>

I understand that it seems that division is just not defined. I expect result to be boost::none if any of two arguments is none - otherwise I want it to be normal double division. Should I just write this myself?


回答1:


Of course such a simple operation as division of doubles is supported.

But you aren't trying to divide doubles. You're trying to divide boost::optional<double>s which is a whole different story.

If you want, you can define a division operator for this. It might look like (untested):

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>();
}

In C++11 (code courtesy of 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;
}

I used a template because now it's also good for int, float, etc.



来源:https://stackoverflow.com/questions/23250430/how-to-divide-boostoptionaldouble

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!