[英]Compile time fail for Typechecking
My understanding of template is that when I write void foo<T>(T x) {...}
and call foo<int>(x);
我对模板的理解是,当我编写
void foo<T>(T x) {...}
并调用foo<int>(x);
and foo<float>(x)
would generate foo(int x)
and foo(float x)
. 和
foo<float>(x)
会生成foo(int x)
和foo(float x)
。
What I want is to type checking before some comparision, but since the compiler generates two version of the function, the comparision part will failed in compiling time. 我想要的是在进行比较之前进行类型检查,但是由于编译器会生成该函数的两个版本,因此比较部分将在编译时失败。
My code is 我的代码是
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";
}
On the othe file I called 在其他文件上,我打电话给
util::print<float>(best_value);
util::print<Point>(best_policy);
Declaration 宣言
std::vector<std::vector<float>> best_value;
std::vector<std::vector<Point>> best_policy;
How should I fix that problem while keeping the print
function and do not have to add the comparision between Point
and float
? 如何在保留
print
功能的同时又不必在Point
和float
之间添加比较项来解决该问题?
只需将std::numeric_limits<float>::lowest()
更改为std::numeric_limits<T>::lowest()
In c++17, you might use if constexpr
for condition known at compile time: 在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";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.