我正在服用 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/