Reputation: 65
I'm very new in C++ and template
. I have a template class in C++03 and I want to force the given type always be unsigned. For example:
template <typename T>
class Test
{
T _var1;
};
I want to force T
to be always unsigned
such as uint8_t, uint16_t, unsigned int, ...
and fail if the given type is signed
. Is this possible to do in C++? If so can someone shows how?
Thank you
Upvotes: 1
Views: 571
Reputation: 72271
This is tricky in C++03 (but easy in C++11). Boost provides a legible and portable way:
#include <limits>
#include <boost/static_assert.hpp>
template <typename T>
class Test
{
BOOST_STATIC_ASSERT_MSG(std::numeric_limits<T>::is_integer &&
!std::numeric_limits<T>::is_signed,
"T must be an unsigned integer type");
// ...
};
Upvotes: 2