C++ 类中的成员模板

16.4.5.Member Templates

Any class (templateor otherwise) may have a member that is itself a class or function template.Suchmembers are referred to as member templates .  Member templates may not bevirtual.

The problem is that the copy constructor and assignmentoperator fix both the container and element type. We'd like to define aconstructor and an assignmember that allow both the container and element typeto vary. When we need a parameter type to vary, we need to define a functiontemplate. In this case, we'll define the constructor and assignmember to take apair of iterators that denote a range in some other sequence. These functionswill have a single template type parameter that represents an iterator type.

Defininga Member Template

A  template memberdeclaration looks like the declaration of any template:

template<class Type> class Queue {

public:

//construct a Queue from a pair of iterators on some sequence

template<class It>

Queue(Itbeg, It end):

head(0),tail(0) { copy_elems(beg, end); }

//replace current  Queue by contentsdelimited by a pair of iterators

template<class Iter> void assign(Iter, Iter);

//rest of Queue class as before

private:

//version of copy to be used by assign to copy elements from iterator range

template<class Iter> void copy_elems(Iter, Iter);

};

The member declaration starts with its own templateparameter list. The constructor and assign member each have a single templatetype parameter. These functions use that type parameter as the type for theirfunction parameters, which are iterators denoting a range of elements to copy.

Defininga Member Template Outside the Class

When we define a member template outside the scope of aclass template, we must include both template parameter lists:

template<class T> template <class Iter>

voidQueue<T>::assign(Iter beg, Iter end)

{

destroy();// remove existing elements in this Queue

copy_elems(beg,end); // copy elements from the input range

}

When a membertemplate is a member of a class template, then its definition must include the class-templateparameters as well as its own template parameters. The class-template parameter listcomes first, followed by the member's own template parameter list.

MemberTemplates Obey Normal Access Control

MemberTemplates and Instantiation

Like any othermember, a member template is instantiated only when it is used in a program.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值