Friend declarations for class templates:
When granting access to all instances of a given template, a declaration of the class template or function template does not need to exist in the scope. When you want to restrict a friendship relationship to a specific instantiation, you must declare the class or function before it can be used in a friend declaration.
template <class T> class test { template <class U> friend ostream& operator<< (ostream &os, const test<U> &obj); //友元的所有实例均具有访问权 ... }; class test; template <class Type> ostream& operator<< (ostream &os, const test<Type> &obj); template <class T> class test { friend ostream& operator<< <T> (ostream &os, const test<T> &obj);//友元为的T类型实例才有访问权 ... };
Template constructor:
In a template class, when the constructor and template constructor exist at the same time, the constructor is called first. A template constructor is called only if its interface is exactly met. The compiler will never treat a template constructor as a constructor, and even if the client does not define a copy constructor, the compiler will generate a default copy constructor.
template <class T> class test { public: test() { cout << "in my test construct" << endl;} test(const test &) { cout << "in my test copy" << endl;} template <class V> test(const test<V> &) { cout << "in my template copy" << endl;} }; int main() { test<int> t1; test<int> t2(t1); test<double> t3(t1); return 0; }
The template
The output structure of the program is:
in my test construct
in my test copy
in my template copy
It is applied in the pair and auto_ptr classes of stl