2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

浮動小数は曖昧に、他の型は正確に比較する

Posted at

浮動小数はあいまいに比較したいけど他の型も比較したい。
そんな曖昧一致を実装する。

# include <iostream>
# include <cmath>
# include <vector>
# include <type_traits>

template <typename A, typename B>
auto comp_arithmetic(A a, B b)
    -> typename std::enable_if<std::is_floating_point<decltype(a - b)>::value,
                               bool>::type {
  return std::abs(a - b) < 1e-10;
}

template <typename A, typename B>
auto comp_arithmetic(A a, B b)
    -> typename std::enable_if<!std::is_floating_point<decltype(a - b)>::value,
                               bool>::type {
  return a == b;
}

template <typename A, typename B>
auto comp(A a, B b)
    -> typename std::enable_if<
          std::is_arithmetic<A>::value &&std::is_arithmetic<B>::value,
          bool>::type {
  return comp_arithmetic(a, b);
}

template <typename A, typename B>
auto comp(A a, B b)
    -> typename std::enable_if<!std::is_arithmetic<A>::value ||
                                   !std::is_arithmetic<B>::value,
                               bool>::type {
  return a == b;
}

int main() {
  std::cout << comp(1, 1) << std::endl;
  std::cout << comp(1, 2) << std::endl;
  std::cout << comp(1., 1) << std::endl;
  std::cout << comp(1. + 1e-14, 1) << std::endl;

  std::vector<int> v(1), u(1);
  v[0] = 1;
  u[0] = 1;
  std::cout << comp(v, u) << std::endl;
  u[0] = 2;
  std::cout << comp(v, u) << std::endl;
  return 0;
}

[Wandbox]三へ( へ՞ਊ ՞)へ ハッハッ

ちょっと冗長になった

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?