计算机二级C++基础(型别对型别的映射)

计算机二级C++基础(型别对型别的映射),第1张

计算机二级C++基础(型别对型别的映射),第2张

是这样的结构:
template
struct type 2 type
{
typedef t original type;
};
假设有如下片段,创建一个t *
模板
t * create(const u & arg)
{
return new t(arg);
}
如果对于“Widget”这样的类,它的ctor有两个参数,比如第二个参数必须是-1(对于旧代码,谁知道:),但是你又不想创建另一个“CreateWidget”方法,那该怎么办?函数不能部分专门化,也就是下面这段代码:
//错误代码
模板
widget * create(const u & arg)
{
return new widget(arg,-1);
}会在VC7下报告:非法使用显式模板参数
只能使用函数重载,比如:
template
t * create(const u & arg,t/* virtual */)
{
return。
}
template
widget * create(const u & arg,widget/* virtual */)
{
return new widget(arg,-1);
}
这样可以解决问题,但问题在于运行时构造考试的开销(虚拟Widget参数)。这时,Type2Type的鼓声出来了。按照书中的说法,它是“一个类型表示和一个可以传递给重载函数的轻量ID”,具体如下:
Template
T * Create(const U & Arg,type 2 type)
{
Return New T .
}
Template
Widget * Create(const U & Arg,type 2 type)
{
Return New Widget(Arg,-1);
}
调用方:
string * pstr = create(" hello ",type 2 type());
Widget *pW = Create(100,type 2 type());

位律师回复
DABAN RP主题是一个优秀的主题,极致后台体验,无插件,集成会员系统
白度搜_经验知识百科全书 » 计算机二级C++基础(型别对型别的映射)

0条评论

发表评论

提供最优质的资源集合

立即查看 了解详情