Fr0stBit
Fr0stBit

Reputation: 1485

Subclass template in C++

I know in java we can do this:

class A<T extends B>
{
...
}

Can we do the same with templates in C++? For example i want to have a templated class A in witch the template T that we pass are subclasses of another class B like the java example above. Any ideas?

EDIT: In one of the answers i was asked to show my code because i had link errors using the answers. Here it is (from deep to the main):

//ComponentManager.h
...
template <typename T,  typename std::enable_if<std::is_base_of<Component, T>::value>::type* = nullptr>
Component* AddComponent(rUUID uuid);
...

//ComponentManager.cpp
...
template <typename T,  typename std::enable_if<std::is_base_of<Component, T>::value>::type* = nullptr>
Component* ComponentManager::AddComponent(rUUID uuid)
{
...
}

//Engine.h
...
template <typename T,  typename std::enable_if<std::is_base_of<Component, T>::value>::type* = nullptr>
void AddComponent(rUUID);
...

//Engine.cpp
...
template <typename T,  typename std::enable_if<std::is_base_of<Component, T>::value>::type* = nullptr>
void Engine::AddComponent(rUUID uuid)
{
...
}
...


//main.cpp
...
e.AddComponent<Position>(a->GetUUID());
...

Upvotes: 1

Views: 525

Answers (2)

David G
David G

Reputation: 96810

Yes, you can use SFINAE:

#include <type_traits>

template <typename T, typename std::enable_if<std::is_base_of<B, T>::value>::type* = nullptr>
class A
{
    // ...
};

Here is a demo showing its use.

Upvotes: 6

catscradle
catscradle

Reputation: 1719

As an alternative to SFINAE you can go with static_assert:

#include <type_traits>
template <typename T>
class A
{
    static_assert(std::is_base_of<BaseClass, T>::value, "error message");
};

Upvotes: 4

Related Questions