【问题标题】:What's the use of the derived class as a template parameter?派生类作为模板参数有什么用?
【发布时间】:2010-10-27 05:28:42
【问题描述】:

这种模式的目的是什么?这叫什么?我第一次看到它时看起来很奇怪,虽然我现在已经看过很多次了。

template<typename Derived>
struct Base {
  //...
};

struct Example : Base<Example> {
  //...
};

【问题讨论】:

    标签: c++ templates terminology crtp static-polymorphism


    【解决方案1】:

    它被称为Curiously Recurring Template 模式,允许静态多态性。

    当您想向特定类添加功能但希望实用程序在一般情况下可用时,它很有用。通过使实用程序依赖并使用模板参数,您可以实现两者。

    【讨论】:

      【解决方案2】:

      我认为您正在引用CRTP。另请参阅here

      【讨论】:

      • @Thomson Tan:请仔细注意@GMan 关于静态多态性的观点。这是很重要的一点。它提供了从基类模拟虚函数调用而没有虚函数开销(如果这很重要的话)
      【解决方案3】:

      【讨论】:

      • 第一个答案4秒;你们都在偷懒!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多