如何编写模板函数,其中参数类型需要继承某个类
How to write a template function where its parameter type is required to be inheriting certain class
是否有可能声明一个模板函数,其中某个类型是从我们说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 << "...";
}
相关文章:
- 继承模板类中的类型别名
- 在运行时检查继承是否只有一种类型和 void*
- C++从外部类继承的嵌套类;不允许使用不完整的类型
- 可以从std::string继承以提供类型一致性吗
- 事件系统:使用类型转换或联合进行继承
- 继承类中的 C++ 成员变量类型重写
- C :可以从类及其受保护的成员类型继承可以继承吗?
- 模板类上的类型继承
- C 类从类型继承
- 在 C++11 中,从私有嵌套类型继承是否合法?
- 模板基类型继承
- C#中从指定类型继承的模板类的等效项是什么
- 为boost mpl列表中的每种类型继承容器
- 从基类和返回类型继承模板
- 从基元类型继承的枚举
- 使用类型继承的数字组的层次结构
- 在任何/某些C++编译器中是否有允许从本机(基本)类型继承的选项
- 创建从不同对象提供的类型继承的类的对象
- c++用这个类作为类型继承类模板
- 我如何从mpl::vector中的所有类型继承