c/c + + template and STL small example series < 2 > template class and friend function
For example, if a class is a template class D, there is a requirement to overload the operator < function of D, then a friend is needed.
Three steps are necessary to achieve such a friend
1. Declare the friend function above the implementation code of template class D
template<typename> class D;//Because D is used in the parameter of friend function, you should declare it here first template<typename T> ostream& operator<< (ostream&, const D<T> &);
2. Declare it as my friend in the implementation code of template class D
//Note that the operator < is followed by < T > friend ostream& operator<< <T>(ostream& ,const D<T>&);
3. Implement friend function
template<typename T> //Note that the operator < is not followed by < T > ostream& operator << (ostream& out,const D<T>& d){ out << d.x; return out; }
Example code:
#include <iostream> using namespace std; template<typename T> class Test{ public: Test(T t) : data(t){} virtual void show() = 0; private: T data; }; template<typename> class D; template<typename T> ostream& operator<< (ostream&, const D<T> &); template<typename T> class D : public Test<T>{ //Note that there are <T> friend ostream& operator<< <T>(ostream& ,const D<T>&); public: //Note not Test(t1) D(T t1, T t2) : Test<T>(t1), x(t2){} void show(){ cout << x << ", " << x << endl; } private: T x; }; template<typename T> ostream& operator << (ostream& out,const D<T>& d){ out << d.x; return out; } int main(void){ Test<int> *p = new D<int>(10, 21); p->show(); D<int> d(10,20); cout << d << endl; return 0; }
Template class inherits non template class, non template class inherits template class
The following examples have no practical significance, just look at grammar.
#include <iostream> using namespace std; class Foo{ public: Foo(int a, int b, int c) : x(a), y(b), z(c){} void show(){ cout << x << "," << y << "," << z << endl; } private: int x, y, z; }; template <typename T> class Goo : public Foo{ public: Goo(T t, int a, int b, int c):Foo(a,b,c), data(t){} void show(){ cout << data << endl; cout << "Goo show" << endl; } private: T data; }; class Hoo : public Goo<int>{ public: Hoo(int a1,int a2,int a3,int a4,int a5): Goo(a1,a2,a3,a4),ho(a5){} void show(){ cout << "Hoo show" << endl; } private: int ho; }; int main(void){ Hoo hoo(1,2,3,4,5); hoo.show(); Goo<string> goo("abc",1,2,3); goo.show(); return 0; }