這是在C++泛型編程(GP)時常常用到的技術,在工作學習中儘可以施展自己的才華。模板--一切皆有可能。
1.隱藏參數細節
模板代碼和使用代碼一般是這樣:
1: template<typename T>
2: class MyClass
3: {
4: private:
5: T m_val;
6: //...
7: };
8:
9: MyClass<int> var1;
10: MyClass<double> var2;
爲了讓客戶端使用時減少針對尖括號,有三種辦法:
1).
1: class ReClass
2: : public MyClass
3: {};
這個方法在ATL/WTL中常常見到。
2).
1: typedef MyClass ReClass;
這個呢,就是STL中的basic_string<>和IO庫的那些class常用的伎倆啦。
3).
1: template<class DefaultClass = YourClass>
2: class MyClass
3: {};
STL容器裏allocator就是使用的這招,不過如果模板參數只有一個(上例),使用的時候還是要帶上尖括號:MyClass<>,而如果是兩個參數及以上,那就很爽啦,就通函數裏的默認參數規則了。
2.Policy策略
Modern C++ Design裏講解的十分細緻,如果有更大的興趣可以去湘西閱讀。Policy是通過讓具體特定行爲的類作爲模板參數,讓莫辦類在處理特定問題時使用該行爲的手段。在做庫的時候Policy手法實在太有用了。
1: template<typename T>
2: class CCompare1
3: {
4: public:
5: static bool Compare(const T &a, const T &b) const;
6: }
7:
8: template<typename T>
9: class CCompare2
10: {
11: public:
12: static bool Compare(const T &a, const T &b) const;
13: }
14:
15: template<typename T, class DefaultComparePolicy = Compare1 >
16: {
17: public:
18: T Min(const T &a, const T &b) const
19: {
20: if( DefaultComparePolicy::Compare(a, b) )
21: return a;
22: else
23: return b;
24: }
25: }
其實呢,在OO世界裏,策略模式就是幹此等事情的。而用GP的手法,是不是更方便了呢?效率是不是高了呢?
3.靜多態
在《C++ template》一書中,這可是一章的內容。模擬動多態,iushi讓行爲看起來是動態綁定的,但綁定工作在編譯階段。從某種程度上說,模擬動態綁定是讓基類知道使用上了繼承類的某些屬性和方法。
1: template<typename T>
2: class TestBase
3: {
4: public:
5: void Test()
6: {
7: return static_cast(this)->Tell();
8: }
9: };
10:
11: class TheTest
12: : public TestBase(TheTest)
13: {
14: public:
15: void Tell()
16: {
17: cout << "TheTest::Tell()" << endl;
18: }
19: };
20:
21: class AnotherTest
22: : public TestBase(AnotherTest)
23: {
24: public:
25: void Tell()
26: {
27: cout << "AnotherTest::Tell()" << endl;
28: }
29: };
其實呢,模板技術遠不止這些皮毛功夫,如果對GP感興趣,完全可以看看STL和BOOST,而C++的1x標準肯定會左右C++泛型技術的發展。拭目以待!