Gabriel
Gabriel

Reputation: 9432

Static Assert if template parameter is of a certain template class

How can I throw a static_assert if template of class A is of a certain templated class NOTALLOWED?

template<typename T>
struct NOTALLOWED{

};

template<typename T>
struct A{
    // static_assert  if T == NOTALLOWED<...>  ??
}


// USING A< NOTALLOWED<int> >  is not allowed for example

the template class A should stay as it is given. I want to prevent A taking a struct NOTALLOWED as template parameter

Thanks a lot!

Upvotes: 0

Views: 139

Answers (2)

Gabriel
Gabriel

Reputation: 9432

Specialize on the special template:

template<typename T>
struct NOTALLOWED{

};

template<typename T>
struct A{
    // normal code
}

template<typename T>
struct A< NOTALLOWED<T> >{
    std::static_assert( sizeof(NOTALLOWED<T>) == -1, "This is not allowed!")
}

Upvotes: 0

Sebastian Redl
Sebastian Redl

Reputation: 71909

You can write is_instantiation traits for specific templates:

template <typename T>
struct is_notallowed_instantiation { constexpr bool value = false; };

template <typename... Args>
struct is_notallowed_instantiation<NOTALLOWED<Args...>> { constexpr bool value = true; };

Then you can static_assert on that.

Upvotes: 1

Related Questions