Friend declaration and template constructor in c++ class template
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

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)
