Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ templates and inheritance, can templates be more selective

Tags:

c++

templates

Can templates be limited to a class that inherits from other class.

for example template<T>, T must inherit from Foo in order to be used in a template function or class.

For example I have a class that requires a controller, this controller will be created in class constructor, but I need to know the type of a controller, and it must conform to an interface (inherit).

View<T> where T is a controller type that must inherit from a generic controller class

like image 594
Anton Stafeyev Avatar asked Oct 29 '25 04:10

Anton Stafeyev


1 Answers

If you want to only allow only Ts that derive from a certain interface you can use SFINAE (substitution failure is not an error). Here is an example:

#include <type_traits>

struct Base {
    virtual ~Base() = default;
};

struct Derived : Base {};

struct NotDerived {};

template <class T, class = std::enable_if_t<std::is_base_of_v<Base,T>>>
struct TClass {};

int main ()
{
    TClass<Derived> tc1;
    // TClass<NotDerived> tc2; // compiler error
}

If you have c++20 concepts then you can do the following:

template<typename T>
concept DerivedFromBase = std::is_base_of_v<Base,T>;

template <DerivedFromBase T>
struct TClass {};

If you use a type which does not inherit from Base you'll get a compiler error.

like image 52
StefanKssmr Avatar answered Oct 31 '25 18:10

StefanKssmr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!