c++ - 来自 boost::operators 的意外行为

标签 c++ boost c++11

我正在服用 boost::operators (clang 2.1, boost 1.48.0) 旋转了一下,遇到了以下我无法解释的行为。似乎当我添加自己的 operator double() const 时我类的方法Ex (因为我想让我的用户在我的类的实例上惯用地使用 static_cast<double>()),我在尝试使用 operator== 时不再遇到编译器错误。不同类之间。事实上,似乎operator==根本没有被调用。

没有operator double() const ,该类完全按预期工作(除了它现在缺少转换运算符),并且我在尝试时收到正确的编译器错误 f == h .

那么添加这个转换运算符的正确方法是什么呢?代码如下。

// clang++ -std=c++0x boost-operators-example.cpp -Wall -o ex  
#include <boost/operators.hpp>
#include <iostream>


template <typename T, int N>
class Ex : boost::operators<Ex<T,N>> {
 public:
  Ex(T data) : data_(data) {};
  Ex& operator=(const Ex& rhs) {
    data_ = rhs.data_;
    return *this;
  };
  T get() {
    return data_ * N;
  };
  // the troubling operator double()
  operator double() const {
    return double(data_) / N;
  };
  bool operator<(const Ex& rhs) const {
    return data_ < rhs.data_;
  };
  bool operator==(const Ex& rhs) const {
    return data_ == rhs.data_;
  };
 private:
  T data_;
};

int main(int argc, char **argv) {
  Ex<int,4> f(1);
  Ex<int,4> g(2);
  Ex<int,2> h(1);

  // this will fail for obvious reasons when operator double() is not defined
  //
  // error: cannot convert 'Ex<int, 4>' to 'double' without a conversion operator

  std::cout << static_cast<double>(f) << '\n';


  std::cout 
    // ok
    << (f == g) 

    // this is the error I'm supposed to get, but does not occur when I have
    // operator double() defined 
    //
    // error: invalid operands to binary expression 
    //  ('Ex<int, 4>' and 'Ex<int, 2>')
    // note: candidate function not viable: no known conversion from 
    //  'Ex<int, 2>' to 'const Ex<int, 4>' for 1st argument
    //   bool operator==(const Ex& rhs) const 
    << (f == h)  
    << '\n';
}

最佳答案

您应该将您的operator double() 标记为显式。这允许静态转换,但在测试相等性(以及其他情况)时会阻止将其用作隐式转换。

关于c++ - 来自 boost::operators 的意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9596386/

相关文章:

c++ - 如何在C++中基于标签运行特定功能?

c++ - std::map 中的对象指针在通过 getter 检索时损坏

c++ - 3D vector C++ 的循环帮助

c++ - 有 C++ 反编译器吗?

c++ - 使用 boost json 读取 json 消息

c++ - 如何使用CMake自动链接Boost库

c++ - 如何获取 std::thread() 的 Linux 线程 ID

c++ - 如何实现线程同步对 vector 的 vector 进行排序?

c++ - 在 C++ 继承中,当指向基类的指针对象指向派生类时,不调用派生类析构函数

c++ - boost spirit 难度,从 XML 示例开始