Reputation: 1250
My understanding of template is that when I write void foo<T>(T x) {...}
and call foo<int>(x);
and foo<float>(x)
would generate foo(int x)
and 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
?
Upvotes: 0
Views: 64
Reputation: 217810
In c++17, you might use if constexpr
for condition known at compile time:
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";
}
}
Upvotes: 2
Reputation: 3506
Just change std::numeric_limits<float>::lowest()
to std::numeric_limits<T>::lowest()
Upvotes: 2