问题描述
如何在 C++ 中使用 CRTP 来避免虚成员函数的开销?
How can I use CRTP in C++ to avoid the overhead of virtual member functions?
推荐答案
有两种方法.
第一个是通过静态指定类型结构的接口:
The first one is by specifying the interface statically for the structure of types:
第二个是避免使用引用到基或指针到基的习惯用法,并在编译时进行接线.使用上面的定义,您可以拥有如下所示的模板函数:
The second one is by avoiding the use of the reference-to-base or pointer-to-base idiom and do the wiring at compile-time. Using the above definition, you can have template functions that look like these:
因此在函数中结合结构/接口定义和编译时类型推导可以让您进行静态分派而不是动态分派.这就是静态多态的本质.
So combining the structure/interface definition and the compile-time type deduction in your functions allows you to do static dispatch instead of dynamic dispatch. This is the essence of static polymorphism.
这篇关于CRTP 避免动态多态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!