I am making a templated Matrix
class, and I have limited the template parameters to the integral and floating point data types by
template class Matrix<int>;
template class Matrix<float>; ..etc
I was implementing a random()
static member function, and to make it uniform random distribution from 0.0
to 1.0
, I used the std::is_floating_point<T>
to limit the use of templates of floating point types. and I thought that the static_assert
will fire if only T
is not a floating point type, but the assertion fails for every template class Matrix<T>;
where T is an integral type.
When I comment out all integral types, it works fine, but I can't do this as I need to be able to make Matrix<T>
instances with T
is an integral type. How would I fix it?
Note that I have provided the template class Matrix<T>
for every integral/floating-point type because I get the undefined reference
error. So I limit the initialization to the integral and floating point types.
// Matrix.cpp
template<typename T>
Matrix<T> Matrix<T>::rand(const size_t& r, const size_t& c) {
Matrix<T> result{ r, c };
static_assert(std::is_floating_point<T>::value,
"result_type must be a floating point type");
const float range_from = 0.0;
const float range_to = 1.0;
std::random_device rand_dev;
std::mt19937 generator(rand_dev());
std::uniform_real_distribution<T> distr(range_from, range_to);
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
result[i][j] = distr(generator);
}
}
return result;
}
//...
template class Matrix<int>;
template class Matrix<long>;
template class Matrix<float>;
template class Matrix<double>;