1#include<typeinfo>
2#include<iostream>
3
4template <typename T>
5class Myclass
6{
7public:
8 template <typename T1> //成员模板
9 void PrintTypeName(T thistype,T1 const othertype);
10
11};
12
13template <typename T>
14template <typename T1> //定义
15void Myclass<T>::PrintTypeName(T thistype,T1 const othertype)
16{
17
18 std::cout<<"thistype is "<<typeid(thistype).name()<<",othertype is "<<typeid(othertype).name()<<std::endl;
19}
20
21
22int main(void)
23{
24 Myclass<int> x ;
25 x.PrintTypeName(10,"hahahah");
26 x.PrintTypeName(10,10.1);
27 x.PrintTypeName(10,false);
28 std::cin.get();
29}
30
31//结果显示
32//thistype is int , othertype is char const*
33//thistype is int , othertype is double
34//thistype is int , othertype is bool
2#include<iostream>
3
4template <typename T>
5class Myclass
6{
7public:
8 template <typename T1> //成员模板
9 void PrintTypeName(T thistype,T1 const othertype);
10
11};
12
13template <typename T>
14template <typename T1> //定义
15void Myclass<T>::PrintTypeName(T thistype,T1 const othertype)
16{
17
18 std::cout<<"thistype is "<<typeid(thistype).name()<<",othertype is "<<typeid(othertype).name()<<std::endl;
19}
20
21
22int main(void)
23{
24 Myclass<int> x ;
25 x.PrintTypeName(10,"hahahah");
26 x.PrintTypeName(10,10.1);
27 x.PrintTypeName(10,false);
28 std::cin.get();
29}
30
31//结果显示
32//thistype is int , othertype is char const*
33//thistype is int , othertype is double
34//thistype is int , othertype is bool
这个是我自己的例子 ,书中的例子是模板类不同类型之间的赋值.
c++ template , p42
这样,参数就不用在定义中确定类型了。