C++类模板中的友元声明及模板构造函数

类模板的友元声明:

当授予给定模板的所有实例的访问权的时候,在作用域中不需要存在该类模板或函数模板的声明。想要限制对特定实例化的友元关系时,必须在可以用于友元声明之前声明类或函数。

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 <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;
}

此处的 template <class V> test(const test<V> &) 函数应该叫做类型转换构造函数,它可以把一个test<T>的类型转换成test<V>,也就是模版参数不同的模版类。这个应用就是比如说我有一个int类型的数组,要用来传递给一个double类型数组的参数,这个构造函数就可以完成这个转换。

程序的输出结构为:

in my test construct

in my test copy

in my template copy

在stl的pair和auto_ptr类中有应用

猜你喜欢

转载自www.linuxidc.com/Linux/2016-10/135830.htm