来自boost ::运算符的意外行为

Nic*_*lko 1 c++ boost c++11

我正在采取boost::operators(铿锵声2.1,提升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';
}
Run Code Online (Sandbox Code Playgroud)

Ala*_*kes 5

你应该operator double()明确标记你的.这允许静态强制转换,但在测试相等性时(以及在其他情况下),它可以防止它被用作隐式转换.

  • 当编译器执行重载解析时,它包含内置运算符 - 包括`operator ==(double,double)`.并且允许对每个参数使用一个隐式转换,因此一个是有效的候选者.而且没有更好的选择,所以选择它. (2认同)