CRTP 避免动态多态

编程入门 行业动态 更新时间:2024-10-09 12:25:28
本文介绍了CRTP 避免动态多态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何在 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:

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. };

第二个是避免使用引用到基或指针到基的习惯用法,并在编译时进行接线.使用上面的定义,您可以拥有如下所示的模板函数:

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:

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

因此在函数中结合结构/接口定义和编译时类型推导可以让您进行静态分派而不是动态分派.这就是静态多态的本质.

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 避免动态多态

本文发布于:2023-08-03 14:48:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1287766.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多态   动态   CRTP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!