歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux綜合 >> Linux資訊 >> 更多Linux >> Scott Meyes 代碼簡單剖析

Scott Meyes 代碼簡單剖析

日期:2017/2/27 14:16:12   编辑:更多Linux
  Scott Meyes 是世界頂尖C++大師,著作有《Effective C++》,《More Effective C++》等,並發表許多著名評論和文章。 關鍵字:traits, partial specialization, 指向成員函數的指針, operator->* DarkSpy 2002/4/24 /*NOTE 請使用g++ 2.97 or higher, Intel C++ 5.0 or higher (6.0 beta for DarkSpy only [DarkSpy report bug]) 編譯,其他主流編譯器無法正確通過, VC 居然出現 26 處錯誤 */ #include #include // 包含 pair 和 make_pair using namespace std; template strUCt MemFuncTraits { }; //partial specialization 1 template struct MemFuncTraits { typedef R ReturnType; typedef O ObjectType; }; //partial specialization 2 template struct MemFuncTraits { typedef R ReturnType; typedef O ObjectType; }; //partial specialization 3 template struct MemFuncTraits { typedef R ReturnType; typedef O ObjectType; }; //partial specialization 4 template struct MemFuncTraits { typedef R ReturnType; typedef O ObjectType; }; template class PMFC { public: typedef typename MemFuncTraits ::ObjectType ObjectType; typedef typename MemFuncTraits ::ReturnType ReturnType; typedef std::pair CallInfo; PMFC(const CallInfo& info) : _callinfo(info) { } //init // 支持無參數類型,ReturnType = MemFuncPreType ReturnType operator()() const { return (_callinfo.first->*_callinfo.second)(); } // 支持具有參數類型 template ReturnType operator()(Param1Type p1) const { return (_callinfo.first->*_callinfo.second)(p1); } private: CallInfo _callinfo; }; template class SmartPtrBase { public: SmartPtrBase(T *p) : ptr(p) { } //init //partial specialization PMFC 並 重載 operator->*. template const PMFC operator->*(MemFuncPtrType pmf) const { return std::make_pair(ptr, pmf); } private: T* ptr; }; template class SP : private SmartPtrBase { // g++ 3.0.2 都有錯誤,改為 public,估計是一個 bug。Intel C++沒有錯誤。 public: SP(T *p) : SmartPtrBase (p) { } using SmartPtrBase ::operator->*; //強制將 private 繼承的 operator->* 繼承為 public 為 main 中調用。 }; class Wombat { public: int dig() { cout << "Digging..." << endl; return 1; } int sleep() { cout << "Sleeping..." << endl; return 5; } int eat() const { cout << "Eatting..." << endl; return 7; }


int move(int op) { cout << "Moving..." << endl; return 9; } }; typedef int (Wombat::*PWMF)(); //for Wombat::dig(0, sleep() typedef int (Wombat::*PWMFC)() const; //for Wombat::eat() const typedef int (Wombat::*PWMF1)(int); //for Wombat::move() main() { SP pw = new Wombat; PWMF pmf = &Wombat::dig; (pw->*pmf)(); // Digging... pmf = &Wombat::sleep; (pw->*pmf)(); // Sleeping... PWMFC pmfc = &Wombat::eat; (pw->*pmfc)(); // Eatting... PWMF1 pmf1 = &Wombat::move; (pw->*pmf1)(2); // Eatting... return 0; } 如果有不同意見或者有任何疑問可以和DarkSpy聯系: [email protected]



Copyright © Linux教程網 All Rights Reserved