模板规范(Template Specifications)

reludson 2004-02-19 09:04:43
Template Specifications
模板规范是一系列参数化的类或函数的定义集。
语法:
模板声明 :
template <模板参数列表 > declaration
模板参数列表:
模板参数
模板参数列表, 模板参数
模板参数:
类型参数
参数声明
类型参数:
class 标识符
typename标识符
模板声明是一系列参数化的类或函数的定义集。
The template declaration specifies a set of parameterized classes or functions.
模板参数列表是用逗号分隔的在模板体中使用的类型(以class identifier, typename identifier,或者 template type的形式出现)或者非类型(non-type)。在声明域中必须是一个函数或类的声明。你可以象实例化一个普通类那样去实例化一个类模板,但是你必须在尖括号中包括模板参数。调用一个功能化的模板不需要特需的语法。
在功能化的模板中,每个模板参数必须在函数的模板参数列表声明中至少出现一次。
模板参数列是一个参数列表,它被用在规定代码中的哪一部分将改变的模板函数之中。例如:
template< class T, int i > class MyStack...
在这种情况下模板能够使用一个类型(class T)和一个常数参数(int i)。模板将再构造函数中使用类型T和常数整型变量i。在MyStack类声明的主体中,你必须参考T标示符。
例如:
Examples
// Example of the template keyword
template <class T, int i> class TestClass {
public:
char buffer[i];
T testFunc(T* p1 );
};

template <class T, int i>
T TestClass<T,i>::testFunc(T* p1) {
return *(p1++)
};

// To create an instance of TestClass
TestClass<char, 5> ClassInst;
下面的例子显示了怎样向一个模板传递一个参数:
template<typename T>
class X {
};

template<template<typename U> class T1, typename T2>
class Y {
};

Y<X, int> aY
typename关键字可以在模板参数列表中使用,下面的模板声明是一样的。
template< class T1, class T2 > class X...
template< typename T1, typename T2 > class X...
下面的模板参数形式是可行的:
template<typename Type> class allocator {};
template<typename Type,
typename Allocator = allocator<Type> > class stack {
};
stack<int> MyStack;
Visual C++支持在模板参数列表中模板参数的复用机制。例如,下面的代码是合法的:
class Y {...};
template<class T, T* pT> class X1 {...};
template<class T1, class T2 = T1> class X2 {...};

Y aY;

X1<Y, &aY> x1;
X2<int> x2;
模板声明自身不会产生代码,它规定了类或函数系列,以及当被其他的代码引用时将要产生的函数或类。
模板声明具有全局或命名区域。
Visual C++执行模板定义的语法检查。Visual C++5.0 和后续的版本能够发现以前的版本不能发现的错误。编译程序现在能够检测到模板定义,但从不实例化的语法错误。
这儿有一个普通的错误列表,它们能够被Visual C++ 4.0编译器编译,但是不能够被Visual C++ 5.0或以后的版本编译。
· 一个用户自定义类型在模板声明声明前就被使用,但是它的声明在模板的第一个实例化或使用之前。
· template<class T> class X {
· //...
· Data m_data; //Error Visual C++ 5.0 or later, Data not defined
· };
·
· class Data {...};
·
· void g() { X<int> x1; }
·
· 解决该问题,只需将类模板X移到数据声明之前。
· 成员函数是在类模板外声明的,而且它从不在类模板内声明。例如:
· template<class T> class X {
· //no mf declared here
· };
·
· //This definition did not cause an error with Visual
· //C++ 4.0, but it will cause an error with Visual
· //C++ 5.0 or later
· //
· template<class T> void X<T>::mf() {...};
· 除了声明是类模板外,类标识将始终被认为是普通类。例如下面的用Visual C++ 5.0或以后的版本而不是用Visual C++ 4.0生成的代码将产生一个错误:
· template<class T> class X {
· friend class Y<T>; //Parsed as Y less-than
· //T greater-than;
· Z<T> mf( ); //Parsed as Z less-than T
· //greater-than;
· };
·
· template<class T> class Y {...};
· template<class T> class Z {...};
·
· X<int> x;
·
· 为了解决此问题,将Y和Z的声明放到X之前。
·
· template<class T> class Y {...};
· template<class T> class Z {...};
·
template<class T> class X {...};
...全文
78 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复

24,854

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 工具平台和程序库
社区管理员
  • 工具平台和程序库社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧