NFRCR
NFRCR

Reputation: 5570

How to allow template class instantiation only if the type T derives from type X?

template <typename T>
class Test
{
};

class A : public X;

class B;

Test<A> a; // OK
Test<B> b; // NOT OK

I would like to accomplish something like this.

Maybe this can be accomplished more easily. Basically, what I need it for is this: the template class T should be able to lock a std::mutex member m_mutex in an object of type T if it exists.

Upvotes: 1

Views: 66

Answers (2)

jrok
jrok

Reputation: 55395

With a static assertion and the appropriate type trait class:

#include <type_traits>

template <typename T>
class Test
{
    static_assert( std::is_base_of<X,T>::value, "T doesn't derive from X!"); 
};

Live example.

Upvotes: 7

David G
David G

Reputation: 96800

You can use std::is_base_of<> with a SFINAE check:

template<
    typename T,
    typename = typename std::enable_if<std::is_base_of<X, T>::value>::type
>
class Test {
   ...
};

Upvotes: 3

Related Questions