如何划分提升::可选<double>?
how to divide boost::optional<double>?
我有这样的代码:
boost::optional<double> result = _ind1.Value() / _ind2.Value();
每个参数也是boost::optional<double>
:
boost::optional<double> Value() {
return value;
}
错误为:
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>
我知道,似乎还没有定义分裂。若两个参数中的任何一个是none
,我希望结果是boost::none
,否则我希望它是正常的二重除法。我应该自己写吗?
当然支持像除法这样简单的操作。
但你并不是想平分双打。你试图划分boost::optional<double>
,这是一个完全不同的故事。
如果需要,可以为此定义除法运算符。它可能看起来像(未经测试):
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提供):
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;
}
我使用了一个模板,因为现在它也适用于int、float等。
相关文章:
- 可组合的lambda/std::函数与std::可选
- 使用gcc从静态链接的文件中查找可选符号
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 在C++中,使用带有 std::optional 参数的函数<T>来表示可选参数是否有意义?
- C++标准是否允许<double>在没有开销的情况下实现 std::可选
- 在 G++ v8.2.0 中使用 std::experimental::可选
- 标准::可选枚举的比较运算符
- 如何使用要传递给 mt19937 的可选随机种子参数设计函数
- 如何在不知道C++中有多少可选参数的情况下在循环中使用va_arg?
- 扩展类中的可选 vir 函数,测试它在运行时是否存在
- C++ win32 如何使密码字段可选并启用复制和粘贴?
- 未定义的引用,尽管存在符号,但 std::experimental::可选
- 命名空间 std:: 不包含可选
- 将可选属性表示为 C++类成员
- 如何使用可选的随机种子参数创建 roll_die() 函数
- 通过跳过可选参数来填充参数包
- 返回arg_min和可选min_val的算法
- std::可选实现为联合与字符[]/aligned_storage
- 如何使用 cin 使 c++ 成为可选?
- 有没有办法在 c++ 中显式调用可选参数?