Вопрос

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
Это было полезно?

Решение

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");
};

Другие советы

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.");
// [...]

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;
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top