C++11 template: How to ensure that the type inherits a class?

Viewed 106

In Java generic, when I want to ensure that the type of some generic class must inherit a class, I can code as below:

public class MyHandler<T extends Serializable> {}

This means that T must extend/implement the class/interface Serializable, otherwise, the compiler will generate an error.

How to get the same thing in C++11? I mean, if I code C++11 as below:

template<typename T>
class MyHandler {}

In this piece of code, T can be any class. But, if I want to tell the class users that T must inherit the class boost::archive::text_oarchive (just like <T extends Serializable> in Java), what can I do?

1 Answers

You can use std::is_base_of for checking.

template<typename T>
class MyHandler {
    static_assert(std::is_base_of<boost::archive::text_oarchive, T>::value, "T must inherit boost::archive::text_oarchive");
};

Since C++20 we can use constraint, e.g.

template<typename T> requires std::is_base_of_v<boost::archive::text_oarchive, T>
class MyHandler {};
Related