gpt4 book ai didi

c++ - 在模板中比较 == !=

转载 作者:太空狗 更新时间:2023-10-29 20:03:38 25 4
gpt4 key购买 nike

在模板类中执行 == 和 != 运算符的正确方法是什么?假设这段代码:

template<typename T>
class C {
T x, y;

public:
C(T a, T b) : x(a), y(b) {}

bool cmp() {
return x == y;
}

};

int main()
{
// OK
C<int> i(1,2);
i.cmp();

// not OK
C<double> d(1.0, 2.0);
d.cmp();

return 0;
}

如果你用 g++ -Wfloat-equal 构建它,你会得到

warning: comparing floating point with == or != is unsafe [-Wfloat-equal]

因为您不能简单地比较浮点变量。


更新

我已经像这样使用 type_traits 和 enable_if 解决了这个问题(感谢@Andrew 和@OMGtechy):

#include <type_traits>
#include <limits>
#include <cmath>
#include <iostream>

using namespace std;

template <typename IntegralType>
typename std::enable_if<std::is_integral<IntegralType>::value, bool>::type
equal(const IntegralType& a, const IntegralType& b) {
return a == b;
}

template <typename FloatingType>
typename std::enable_if<std::is_floating_point<FloatingType>::value, bool>::type
equal(const FloatingType& a, const FloatingType& b) {
return std::fabs(a-b) < std::numeric_limits<FloatingType>::epsilon();
}

template<typename T>
class C {
T x, y;

public:
C(T a, T b) : x(a), y(b) {}

bool cmp() {
return equal(x, y);
}

};

int main()
{
// OK
C<int> i(1,2);
cout << i.cmp() << endl;

// not OK
C<double> d(1.0, 1.0);
cout << d.cmp() << endl;

return 0;
}

最佳答案

这个问题好像在问两件事:

  1. 如何在不使用运算符== 的情况下进行浮点比较
  2. 如何根据传递给模板的类型修改模板的行为。

第二个问题的一个答案是使用类型特征。下面的代码针对您的情况演示了这一点,为一般类型(使用 ==)提供了 comparison_traits,并使用容差(也回答了第一个问题)为 double 提供了专门化。

#include <cmath>

template <typename T> struct comparison_traits {
bool equal(const T& a, const T& b) {
return a == b;
}

// etc.
};

template<> struct comparison_traits<double> {
bool equal(const double& a, const double& b) {
return fabs(a - b) < 1e-15; // or whatever...
}
};

template <typename T>
class C {
T x, y;

public:
C(const T& a, const T& b) : x(a), y(b) {}

bool cmp() {
return comparison_traits<T>::equal(x, y);
}
};

int main() {
// OK
C<int> i(1, 2);
i.cmp();

// Now OK too...
C<double> d(1.0, 2.0);
d.cmp();

return 0;
}

其他选项包括:

  • 提供一个允许您指定比较函数的模板参数,默认为 std::equal_to

  • 将您的模板专门用于 double,以便您可以编写 cmp() 的不同实现

关于c++ - 在模板中比较 == !=,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27228813/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com