C++ 中的 CRTP 手法 - uulm's Blog
C++ 中的 CRTP 手法
CRTP (curiously recurring template pattern) 是指类 C 继承另外一个使用类 C 具现的模板类这种手法。
比如这样:
template<struct D> struct B {}; struct C : B<C> {};
CRTP 可以用来避免一个庞大的类文件和繁复的继承关系
比如可以把
struct C { void f1(); void f2(); //...... void fn(); };
精简为:
template<struct D> struct f1_ { void f1(); }; template<struct D> struct f2_ { void f2(); }; //...... template<struct D> struct fn_ { void fn(); }; struct C_279 : f2_<C>, f7_<C>, f9_<C> {};
将实现打散到不同的模块类中去,精简代码,在使用时临时组装新类。
模块类预制时如果与别的模块类有耦合,实现则稍有技巧,需要 static_cast 一下:
template<struct D> struct m1 { int f1() const { return 1+ (static_cast<D const&>(*this)).f2(); } }; template<struct D> struct m2 { int f2() const { return 1; } }; struct C : m1<C>, m2<C> {};
这种方法还可以用作 Expression Template, 在 std::valarray, boost::ublas 以及 mtl 中可以大量看到,感兴趣的读者可以稍作研究
Thu, 17 Oct 2019 16:17:28 +0200
You are talented. I like reading your posts. Bye!
Mon, 22 Feb 2021 18:22:56 +0100
This section can be a piece of very good knowledge for CS students like me. https://justplantprotein.com Actually, this blog is good for learning. Thanks for sharing this data. It is really educational. Articles like this help me to improve my learning of C++.
Sat, 12 Jun 2021 19:53:06 +0200
In vitro fertilization (IVF) is a complex series of procedures used to help with fertility or prevent genetic problems best ivf treatment in kerala and assist with the conception of a child. During IVF , mature eggs are collected from ovaries and fertilized by sperm in a lab.
Mon, 02 May 2022 22:30:44 +0200
I’m keen on this post, enjoyed this one thank you posting . Merchant Services Commission Structure
==============================================
Good day very cool web site!! Man .. Excellent .. Superb .. I’ll bookmark your web site and take the feeds additionally…I am glad to find a lot of useful information right here in the put up, we want develop more strategies in this regard, thanks for sharing. . . . . . How to Sell Credit Card Processing