如何在C++中使用CRTP来避免虚拟成员函数的开销?
发布于 2008-11-04 19:02:57
有两种方法。
第一种方法是静态地为类型结构指定接口:
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.
};第二种方法是避免使用引用基址或指向基址的指针,而是在编译时进行连接。使用上面的定义,您可以拥有如下所示的模板函数:
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因此,在函数中结合结构/接口定义和编译时类型推断,可以进行静态调度,而不是动态调度。这就是静态多态的本质。
发布于 2008-11-04 17:49:28
我一直在寻找关于CRTP的像样的讨论。Todd Veldhuizen的Techniques for Scientific C++是这个(1.3)和其他许多高级技术(如表达式模板)的很好的参考资料。
此外,我发现你可以在谷歌图书上阅读到C++ Gems的大部分原创文章。也许现在还是这样。
发布于 2008-11-04 16:11:40
我不得不去找CRTP。然而,做完这些之后,我发现了一些关于Static Polymorphism的东西。我怀疑这就是你问题的答案。
事实证明,ATL非常广泛地使用了这种模式。
https://stackoverflow.com/questions/262254
复制相似问题