Home  >  Article  >  类库下载  >  Friend declaration and template constructor in c++ class template

Friend declaration and template constructor in c++ class template

高洛峰
高洛峰Original
2016-10-12 15:52:481652browse

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 test(const test &) function here should be called the type conversion constructor, which can convert the type of a test into test, that is, a template class with different template parameters. This application is, for example, if I have an array of type int and want to pass it to a parameter of type double array, this constructor can complete the conversion.

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


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Related articles

See more