Did you like how we did? Rate your experience!

4.5

satisfied

46 votes

How do I check if the template type T, is of the integer type and?

This is a classic problem and it is important to know how to handle this. The full details: (A) First of all you need to be able to discriminate between the types that are acceptable and the one that are. The method for that is to uses Trait (computer programming). It goes that way. Default types you do not want even to consider so you wrote template struct is_integral_type { }; For the floating points you want to exclude: template struct is_integral_type { static const bool value = false; }; template struct is_integral_type { static const bool value = false; }; For the type you want to accept you do: template struct is_integral_type { static const bool value = true; }; In that case as User-11956034714365873629 pointed out, there is already an implementation of that trait with std::is_integral. However, you might need your own trait so it is important to be able to write the above down. (B) Now, in your code you wrote the key statement. static_assert(is_integral_type::value, "Requires T to be an integer type"); If your type T is not acceptable then compilation fails and a clear error message is reported. In my opinion it is very important to use static_assert. Two reasons: It avoids compilation errors down the line. It is best to have the error at the earliest stage in the compilation. The static_assert construction is thus a good thing in order to avoid very large compilation template errors. It avoid real errors in the program (i.e. error happening past the compilation). Let me give a specific example. I had a function computing the inverse of a n\times n matrix A. If the matrix A is integral and of determinant 1 then the inverse A^{-1} is also integral. However, if one uses Gaussian elimination for this then the computation has rational elements even if the final result is integral. Since the program used operations a / b but those have different meaning for double (it is really division) and integral (it is Euclidean division) the compilation went ok but the results were wrong. Thus I had wrong inverse but only happening for specific matrices since for small matrices no fraction occured. By having static_assert((not is_integral_type::value), "Requires T to be a field type"); the error was caught at the compilation. How the problem was solved is another story.

100%
Loading, please wait...