modern C++ design type2type 笔记

来源:互联网 发布:mysql ibata文件 编辑:程序博客网 时间:2024/06/06 15:50
#include <iostream>#include <string>using namespace std;template<class T>struct Type2Type{    typedef T OrgT; };class Widget{    public:         Widget(string str, int n)        {                   cout<<str<<":"<<n<<endl;                 }        }; template<class T, class U> T *Create(const U &org, Type2Type<T>) {    return new T(org);  }template<class T>Widget *Create(const T&org, Type2Type<Widget>){    return new Widget(org, -1); }int main(){    string *str = Create("hello", Type2Type<string>());    cout<<*str<<endl;    delete str;    Widget *wid = Create("I am Widget", Type2Type<Widget>());    delete wid;}~                                                                                                                                                     


一句话总结Type2Type,就是用自定义的空模板,完成了函数重载的工作。