#include<iostream> #include<string> #include<typeinfo> using namespace std; template <class Name,class Hobby,class Age> //类模板做函数的参数 class Dog{ private: Name m_name; Hobby m_hobby; Age m_age; public: Dog(Name name,Hobby hobby,Age age){ this->m_name=name; this->m_hobby=hobby; this->m_age=age; } void display(){ cout<<"m_name:"<<m_name<<" m_hobby:"<<m_hobby<<" m_age:"<<m_age<<endl; } }; void dis1(){ Dog<string,string,int> dog1("小灰","吃",2); dog1.display(); } // 参数模板化 template<class Name,class Hobby,class Age> void dis2(Dog<Name,Hobby,Age> dog){ // 传递类 cout << typeid(Name).name() << endl; cout << typeid(Hobby).name() << endl; cout << typeid(Age).name() << endl; dog.display(); } // 整体类型化 template<class T> void dis3(T &dog){ // 传递类 cout << typeid(T).name() << endl; dog.display(); } // 指定传入类型 void dis4(Dog<string,string,int> dog) { // 传递数据类型 dog.display(); } int main(){ Dog<string,string,int> dog2("小黑","睡",1); dis1(); dis2(dog2); dis3(dog2); dis4(dog2); return 0; }
注意:该程序在乌班图下会出现错位如图所示:
解决方法是:在生成的test文件下打开终端执行 ./test | c++filt -t 或在生成的a.out文件夹下执行./a.out | c++filt -t结果如下:
c++ filt使用方法:在终端执行:man C++FILT 命令 会出现: