类型检查的编译时失败
Compile time fail for Typechecking
我对模板的理解是,当我编写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
功能的同时解决这个问题,而不必在Point
和float
之间添加比较?
只需将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";
}
}
相关文章:
- luaL_dofile在已知良好的字节码上失败,可以使用未编译的版本
- 包含模板文件的递归会导致编译失败
- 提升 1.64 单元测试编译失败
- 如何让谷歌测试正常运行。测试总是失败。(它不会编译)
- 运行时检查失败 #0 用于运行时重新编译
- C++模板的模板编译失败
- 使用已删除的函数进行编译失败,并显示 uclibc
- MinGW-w64 编译失败,nullptr_t
- 使用提升线程时编译失败
- 编译花絮 g++, clang++, 使用 libboost -- g++8 编译失败时 g++7 成功;
- 编译成功,使用 clang 5.0.1/6.0.0 ,在 5.0.2/6.0.1 时失败
- CMake + Qt,moc 编译失败,无法实现 QMetaObject 方法(编译器找不到基本 ui 对象的标头?
- 带有引用的std::tuple在clang中编译失败,但在gcc中编译失败
- bitbake-grpc交叉编译/配置失败,错误为c-ares::care引用文件/usr/lib/libcares.s
- 解决由于在哈希函数中使用了不完整的类型而导致的编译失败
- 将XCode升级到verison 11.1后,C++编译失败
- 继承的构造函数,在 clang++3.9 中编译,在 g++ 7 中失败
- C++:此代码可以编译,但引发运行时检查失败 #2 - 围绕变量周围的堆栈'num'已损坏。发生
- 添加类型名会导致程序编译失败
- 将 qi::lexeme 添加到灵气中的规则时编译失败