C ++:从模板参数继承类 [英] C++: Inherit class from template parameter

查看:140
本文介绍了C ++:从模板参数继承类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近看到了以下C ++代码段

I recently saw the following C++ code-snippet

template <class B>
class A : public B
{
   ...
};

我想知道在哪种设置中这样的设计是好的做法?

and I am wondering in which setting such a design is good practice?

据我了解,以超类作为模板参数可以使 A 的用户在实例化对象时选择超类。 A

The way I understand it, is that having the superclass as a template parameter allows users of A to choose a superclass when instantiating an object of A.

但是,如果是这种情况,对所有类都使用通用的超类 C 会不会更好( B )用作模板参数,并具有 A 扩展 C 吗?

But if this is the case, wouldn't it be better to have a common superclass C for all the classes (B) which are used as the template argument and have A extend C ?

推荐答案

它通常用于实现静态多态性

用例为:

  • Policy-based design
  • Curiously recurring template pattern
  • Barton–Nackman trick

通常,您可以从动态多态中受益,而无需虚拟函数的额外运行时成本。但是,只有在编译时就可以确定具体类型时,它才有用。

In general you have the benefits from dynamic polymorphism, without the extra runtime costs of virtual functions. But it's only useful if the concrete type can be determined at compile time.

这篇关于C ++:从模板参数继承类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆