Search code examples
c++boostboost-optional

how to divide boost::optional<double>?


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?


Solution

  • 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.