Search code examples
c++templatesinheritancereturn

How to write a template function where its parameter type is required to be inheriting certain class


Is it possible to declare a template function where a certain type is derived from let's say B?

My goal is to achieve something like this:

template<class T : std::ostream> void write(T os) {
    os << "...";
} 

template<class T : std::string> void write(T s) {
   // ...
}

Edit: I know it is not a solid example since it is not usual to derive from a string, but note that it's just a example.

So any solution like a workaround is welcome, however I would like to be able to explicit instantiate the template functions.


Solution

  • Yes, using C++11 <type_traits> it can be achieved.
    If you only have C++03, you can use Boost's <type_traits> instead.

    template <typename T>
    typename std::enable_if<std::is_base_of<std::ostream, T>::value>::type
    write(T& os) {
    }