首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >避免动态多态的CRTP

避免动态多态的CRTP
EN

Stack Overflow用户
提问于 2008-11-04 16:07:47
回答 5查看 27.7K关注 0票数 90

如何在C++中使用CRTP来避免虚拟成员函数的开销?

EN

回答 5

Stack Overflow用户

发布于 2008-11-04 19:02:57

有两种方法。

第一种方法是静态地为类型结构指定接口:

代码语言:javascript
复制
template <class Derived>
struct base {
  void foo() {
    static_cast<Derived *>(this)->foo();
  };
};

struct my_type : base<my_type> {
  void foo(); // required to compile.
};

struct your_type : base<your_type> {
  void foo(); // required to compile.
};

第二种方法是避免使用引用基址或指向基址的指针,而是在编译时进行连接。使用上面的定义,您可以拥有如下所示的模板函数:

代码语言:javascript
复制
template <class T> // T is deduced at compile-time
void bar(base<T> & obj) {
  obj.foo(); // will do static dispatch
}

struct not_derived_from_base { }; // notice, not derived from base

// ...
my_type my_instance;
your_type your_instance;
not_derived_from_base invalid_instance;
bar(my_instance); // will call my_instance.foo()
bar(your_instance); // will call your_instance.foo()
bar(invalid_instance); // compile error, cannot deduce correct overload

因此,在函数中结合结构/接口定义和编译时类型推断,可以进行静态调度,而不是动态调度。这就是静态多态的本质。

票数 142
EN

Stack Overflow用户

发布于 2008-11-04 17:49:28

我一直在寻找关于CRTP的像样的讨论。Todd Veldhuizen的Techniques for Scientific C++是这个(1.3)和其他许多高级技术(如表达式模板)的很好的参考资料。

此外,我发现你可以在谷歌图书上阅读到C++ Gems的大部分原创文章。也许现在还是这样。

票数 18
EN

Stack Overflow用户

发布于 2008-11-04 16:11:40

我不得不去找CRTP。然而,做完这些之后,我发现了一些关于Static Polymorphism的东西。我怀疑这就是你问题的答案。

事实证明,ATL非常广泛地使用了这种模式。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/262254

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档