16.4.2 非类型形参的模板实参
//Template1.h
#include
using namespace std;
#ifndef TEMPLATE1_H
#define TEMPLATE1_H
template
class Screen{
public:
Screen():screen(hi*wid,'#'),cursor(0),height(hi),width(wid){}
private:
string screen;
string::size_type cursor;
string::size_type height,width;
};
#include "Template1.cpp"
#endif
//Template1.h
#include
using namespace std;
#ifndef TEMPLATE1_H
#define TEMPLATE1_H
template
class Screen{
public:
Screen():screen(hi*wid,'#'),cursor(0),height(hi),width(wid){}
private:
string screen;
string::size_type cursor;
string::size_type height,width;
};
#include "Template1.cpp"
#endif//CP.cpp
Screen<100,200> hp;
//CP.cpp
Screen<100,200> hp;非类型模板实参必须是编译时常量表达式。
16.4.3 类模板中的友元声明
在类模板中可以出现三种友元声明:
(1)普通非模板类或函数的友元声明,将友元关系授予明确指定的类或函数。
(2)类模板或函数模板的友元声明,授予对友元所有实例的访问权。
(3)只授予对类模板或函数模板的特定实例的访问权的友元声明。
1. 普通友元
非模板类或非模板函数可以是类模板的友元。
template
class Screen{
public:
Screen():screen(hi*wid,'#'),cursor(0),height(hi),width(wid){}
private:
string screen;
string::size_type cursor;
string::size_type height,width;
friend class Base;
};
template
class Screen{
public:
Screen():screen(hi*wid,'#'),cursor(0),height(hi),width(wid){}
private:
string screen;
string::size_type cursor;
string::size_type height,width;
friend class Base;
};
2. 一般模板友元关系
#include
#include "Class.h"
#include "Queue.h"
using namespace std;
template
class Screen{
public:
Screen():screen(hi*wid,'#'),cursor(0),height(hi),width(wid){}
private:
string screen;
string::size_type cursor;
string::size_type height,width;
template
};
#include
#include "Class.h"
#include "Queue.h"
using namespace std;
template
class Screen{
public:
Screen():screen(hi*wid,'#'),cursor(0),height(hi),width(wid){}
private:
string screen;
string::size_type cursor;
string::size_type height,width;
template
};友元可以是类模板或函数模板。
3. 特定的模板友元关系
除了将一个模板的所有实例设为友元,类也可以只授予对特定实例的访问权。
#include
#include "Class.h"
#include "Queue.h"
using namespace std;
template
class Screen{
public:
Screen():screen(hi*wid,'#'),cursor(0),height(hi),width(wid){}
private:
string screen;
string::size_type cursor;
string::size_type height,width;
friend class Queue
};
#include
#include "Class.h"
#include "Queue.h"
using namespace std;
template
class Screen{
public:
Screen():screen(hi*wid,'#'),cursor(0),height(hi),width(wid){}
private:
string screen;
string::size_type cursor;
string::size_type height,width;
friend class Queue
};4. 声明依赖性
当授予对给定模板的所有实例的访问权的时候,在作用域中不需要存在该类模板或函数模板的声明。实际上,编译器将友元声明也当作类或函数的声明对待。
想要限定对特定实例化的友元关系时,必须在可以用于友元声明之前声明类或函数。
#include
#include "Class.h"
using namespace std;
template
class Screen{
public:
Screen():screen(hi*wid,'#'),cursor(0),height(hi),width(wid){}
private:
string screen;
string::size_type cursor;
string::size_type height,width;
template
};
#include
#include "Class.h"
using namespace std;
template
class Screen{
public:
Screen():screen(hi*wid,'#'),cursor(0),height(hi),width(wid){}
private:
string screen;
string::size_type cursor;
string::size_type height,width;
template