gpt4 book ai didi

c++ - 仅为派生自单个基类的类定义模板函数

转载 作者:可可西里 更新时间:2023-11-01 17:38:32 26 4
gpt4 key购买 nike

我有一个基类 Base ,许多其他类将派生自。我想定义:

template<typename Derived>
ostream &operator<< (ostream &o, Derived &derived) {
}

但仅适用于从 Base 派生的类.我需要所有以前定义的 operator<<用于其他类型。怎么做?那可能吗?

我无法创建 ostream &operator<< (ostream &o, Base &base) ,因为我需要在某些类型特征中使用确切的类型。有什么方法可以在将值作为基类型传递的同时“推送”派生类型吗?

最佳答案

http://www.boost.org/doc/libs/1_46_0/libs/utility/enable_if.html

http://www.boost.org/doc/libs/1_42_0/libs/type_traits/doc/html/boost_typetraits/reference/is_base_of.html

template<typename Derived>
typename enable_if<is_base_of<Base, Derived>, ostream&>::type
operator<< (ostream &o, Derived &derived)
{

}

关于c++ - 仅为派生自单个基类的类定义模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5108704/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com