1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| template <typename Derived> class Base { public: void show(void) { static_cast<Derived*>(this)->show(); } protected: void show(void) { std::wcout << L"Base::show()" << std::endl; } };
class Client : public Base<Client> { public:
}; int main() { Client client; client.show(); return 0; }
|
输出:
2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| template <typename Derived> class Base { public: void show(void) { static_cast<Derived*>(this)->show(); } protected: void show(void) { std::wcout << L"Base::show()" << std::endl; } };
class Client : public Base<Client> { public: void show(void) { std::wcout << L"Client::show()" << std::endl; } }; int main() { Client client; client.show(); return 0; }
|
输出:
静态多态
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| #include <iostream>
template<class Derived> struct Algo { void run() { pre(); static_cast<Derived*>(this)->impl(); post(); } void pre() { } void post() { } };
struct AlgoA : Algo<AlgoA> { void impl() { std::cout << "AlgoA fast path\n"; } };
struct AlgoB : Algo<AlgoB> { void impl() { std::cout << "AlgoB precise path\n"; } };
int main() { AlgoA a; a.run(); AlgoB b; b.run(); }
|
实际场景
WTL、ATL(活动模板库,90年代的,用于COM)