c++ - 如何划分boost::optional<double>?

标签 c++ boost boost-optional

我有这样的代码:

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>

我知道似乎没有定义除法。我希望结果是 boost::none如果两个参数中的任何一个是 none - 否则我希望它是正常的双除法。我应该自己写这个吗?

最佳答案

当然支持double除法这种简单的操作。

但您并不是要分 double 。你试图划分 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 等。

关于c++ - 如何划分boost::optional<double>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23250430/

相关文章:

c++ - 无法同时在 IPv4 和 IPv6 中将套接字绑定(bind)到端口

macos - 如何在 Mac 上卸载 Boost?

boost - 如何查看 Boost.Build 调用的 g++ 命令行 (1.33.1)

c++ - boost optional 承认继承?

c++ - 将 boost::optional 与 boost::adaptors::indirected 一起使用

c++ - boost::optional - 将 boost::in_place 用于构造函数通过引用获取其他对象的对象

c++ - 关于四舍五入和产生正确输入的代码帮助

c++ - 如何确保一个函数只被调用一次

c++ - 如何在 boost::gil 中使用 alpha channel 调整 png 图像的大小

c++ - 使用 boost c++ 解析 XML