《C++Primer PLus 第五版》读书笔记3(九)

2014-11-24 10:39:59 · 作者: · 浏览: 8


int _tmain(int argc, _TCHAR* argv[])
{
counts();
CHasFriend hfil( 10 );
CHasFriend hfi2( 20 );
CHasFriend hfdb( 10.5 );

report( hfil );
report( hfi2 );
report( hfdb );

cout << "counts() output :" << endl;
counts();
cout << "counts() output :" << endl;
counts();


return 0;
}
声明中的<>指出这是模板具体化。对于report(),<>可以为空,这是因为可以从函数参数推断出模板类型参数(CHasFriend)。不过,也可以使用report< CHasFriend >( CHasFriend& )。但counts()函数没有参数,因此必须使用模板参数句法()来指明其具体化。还需要注意的是,TT是CHasFriend类的参数类型。

3.非约束(unbound)模板友元,即友元的所有具体化都是类的每一个具体化的友元
[cpp]
// testTemplateFriend4.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "iostream"
using namespace std;
#include "string"

template
class CManyFriend
{
public:
CManyFriend( const T& i ) : item( i )
{
}
template friend void show( C&, D& );
private:
T item;
};

templatevoid show( C& c, D& d )
{
cout << c.item << " " << d.item << endl;
}



int _tmain(int argc, _TCHAR* argv[])
{
CManyFriend hfil( 10 );
CManyFriend hfil2( 20 );
CManyFriend hfdb( 10.5 );

cout << "hfil, hfil2:";
show( hfil, hfil2 );

cout << "hfil2, hfdb:";
show( hfil2, hfdb );

return 0;
}
前面的1、2,int类具体化获得int函数具体化,依此类推。通过在类内部声明模板,可以创建非约束友元函数,即每个函数具体化都是每个类具体化的友元。对于非约束友元,友元模板类型参数与模板类类型参数是不同的:
template friend void show( C&, D& );
但前提是必须在类内部声明模板