Reputation: 86165
How can I make static_assert
for specific type constraint?
Currently I want to make my template only for unsigned int
type, but not signed int
type. Or, just only for integral type, or specific type names. static_assert(sizeof(int))
offers only size based assertion, and I don't know how to perform any extra checks.
I am using Clang with its libc++
in Xcode 4.6.2. Here's current compiler information on command-line.
Apple LLVM version 4.2 (clang-425.0.28) (based on LLVM 3.2svn)
Target: x86_64-apple-darwin12.3.0
Thread model: posix
Upvotes: 4
Views: 5593
Reputation: 4120
To check for all integral types, the following can be used:
#include <type_traits>
// [...]
static_assert(std::is_integral<T>::value, "The type T must be an integral type.");
// [...]
Upvotes: 2
Reputation: 474566
That's not really what static_assert
is for, but you can do it like this:
template<typename T>
struct Type
{
static_assert(std::is_same<T, unsigned int>::value, "bad T");
};
Or, if you just want T
to be an unsigned integral type of some sort (not specifically unsigned int
):
template<typename T>
struct Type
{
static_assert(std::is_unsigned<T>::value, "bad T");
};
Upvotes: 10
Reputation: 2906
Here's a scaffold:
#include <type_traits>
template<typename TNum>
struct WrapNumber
{
static_assert(std::is_unsigned<TNum>::value, "Requires unsigned type");
TNum num;
};
WrapNumber<unsigned int> wui;
WrapNumber<int> wi;
Upvotes: 1