如何编写模板函数,其中参数类型需要继承某个类

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

本文关键字:类型 继承 参数 何编写 函数      更新时间:2023-10-16

是否有可能声明一个模板函数,其中某个类型是从我们说B派生的?

我的目标是实现这样的东西:

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

编辑:我知道这不是一个坚实的例子,因为它不是通常从字符串派生,但请注意,这只是一个例子。

因此,任何解决方案,如变通是受欢迎的,但我希望能够显式实例化模板函数。

是的,使用c++ 11 <type_traits>可以实现。
如果你只有c++ 03,你可以使用Boost的<type_traits>

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

任何从std::ostream派生的对象都可以用作

的形参。
void write(std::ostream os) {
    os << "...";
}