#include <iostream>
using namespace std;
template <class T1,class T2>
class Test
{
private:
T1 m_a;
T2 m_b;
public:
Test(T1 a,T2 b)
{
m_a = a;
m_b = b;
}
T1 get_val1();
T2 get_val2();
};
template<class T1,class T2>
T1 Test<T1,T2>::get_val1()
{
return m_a;
}
template<class T1,class T2>
T2 Test<T1,T2>::get_val2()
{
return m_b;
}
int main()
{
Test<double,int>a(1.2,3);
cout << a.get_val1() << endl;
cout << a.get_val2() << endl;
return 0;
}
栈操作
#include <iostream>
using namespace std;
template<class T>
class Stack
{
private:
int Max_size;
int top;
T * stackptr;
public:
Stack(int s);
~Stack(){delete [] stackptr;}
bool is_Empty() const {return (top == -1);}
bool is_Full() const {return (top == Max_size);}
bool push(const T& t);
bool pop(T& t);
};
template<class T>
Stack<T>::Stack(int s)
{
Max_size = s > 0 ? s : 10;
top = -1;
stackptr = new T[Max_size];
}
template<class T>
bool Stack<T>::push(const T& t)
{
if(!is_Full())
{
top++;
stackptr[top] = t;
return true;
}
return false;
}
template <class T>
bool Stack<T>::pop(T& t)
{
if(!is_Empty())
{
t = stackptr[top--];
return true;
}
return false;
}
int main()
{
Stack<double> double_stack(5);
double f = 0.1;
/*for(int i = 0; i < 5; i++)
{
double_stack.push(f);
f += 1;
}*/
while(double_stack.push(f))
{
cout << f << endl;
f = f + 1;
}
while(double_stack.pop(f))
{
cout << f << endl;
}
return 0;
}
普通类 -> 模板类
#include <iostream>
using namespace std;
class Base
{
private:
int m_a;
protected:
int m_b;
public:
Base(int a,int b)
{
m_a = a;
m_b = b;
}
void show()
{
cout << m_a << "," << m_b << endl;
}
};
template<class T>
class Derived:public Base
{
private:
T m_t;
public:
Derived(T t):Base(0,0)
{
m_t = t;
}
T get_t()
{
return m_t;
}
};
int main()
{
Derived<double> d(1.2);
d.show();
double a = d.get_t();
cout << a << endl;
return 0;
}
模板类->模板类
#include <iostream>
using namespace std;
template <class T>
class Base
{
public:
void test(T t)
{
cout << "base::t :" << t << endl;
}
};
template<class T1,class T2>
class Derived:public Base<T2>
{
public:
void test2(T1 t1, T2 t2)
{
cout << "Derived::" << t1 << "," << t2 << endl;
}
};
int main()
{
Derived<int,double> d1;
d1.test(1.23);
d1.test2(12,34);
return 0;
}