类型检查的编译时失败

Compile time fail for Typechecking

本文关键字:失败 编译 检查 类型      更新时间:2023-10-16

我对模板的理解是,当我编写void foo<T>(T x) {...}并调用foo<int>(x);时,foo<float>(x)会产生foo(int x)foo(float x)

我想要的是在某些比较之前进行类型检查,但由于编译器生成了函数的两个版本,因此比较部分将在编译时间内失败。

我的代码是

template <typename T>
      void print(const std::vector<std::vector<T>>& matrix) {
          std::cout << std::setprecision(3) << std::fixed;
          for (int j=0; j < matrix[0].size(); j++) {
              for (int i=0; i < matrix.size(); i++) {
                  // Fail on this line ↓
                  if ((std::is_floating_point<T>::value) &&
                          (matrix[i][j] == std::numeric_limits<float>::lowest())) {
                      std::cout << "✗ ";
                      continue;
                  }
                  std::cout << matrix[i][j] << " ";
              }
          }
          std::cout << "n";
      }

在我调用的文件中

util::print<float>(best_value);
util::print<Point>(best_policy);

声明

std::vector<std::vector<float>> best_value;
std::vector<std::vector<Point>> best_policy;

我应该如何在保持print功能的同时解决这个问题,而不必在Pointfloat之间添加比较?

只需将std::numeric_limits<float>::lowest()更改为std::numeric_limits<T>::lowest()

在 c++17 中,你可以使用 if constexpr 表示编译时已知的条件:

template <typename T>
void print(const std::vector<std::vector<T>>& matrix) {
    std::cout << std::setprecision(3) << std::fixed;
    for (const auto& row : matrix) {
        for (const auto& e : row) {
            if constexpr (std::is_floating_point<T>::value)) {
                if (e == std::numeric_limits<float>::lowest())) { // T instead of float?
                    std::cout << "✗ ";
                    continue;
                }
            }
            std::cout << e << " ";
        }
        std::cout << "n";
    }
}