问题描述
我有这样的code:
boost::optional<double> result = _ind1.Value() / _ind2.Value();
每个arg是的boost ::可选&LT;双&GT;
太:
boost::optional<double> Value() {
return value;
}
错误是:
错误1错误C2676:二进制'/':'的boost ::可选&LT; T&GT;'不定义此运算符或转换到类型接受的predefined运营商
2智能感知:没有操作/匹配这些操作数
操作数类型是:推动::可选&LT;双&GT; /升压::可选&LT;双&GT;
据我所知,似乎分工只是没有定义。我预计结果为的boost ::无
如果有两个参数是无
- 否则,我想这是正常的双师。我是不是应该写这个自己?
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?
推荐答案
当然,这样一个简单的操作双打的分工是支持的。
Of course such a simple operation as division of doubles is supported.
但你是不是想分裂双打。你企图分裂的boost ::可选&LT;双重方式&gt;
■哪些是一个完全不同的故事
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>();
}
在C ++ 11(Yakk的code提供):
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.
这篇关于如何划分的boost ::可选&LT;双&GT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!