栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

template用法及常见错误

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

template用法及常见错误

一,泛化基本数据类型

主要用于:不同的数据类型,相同的实现方法,可以用template封装成一个API。

实例:

class Iprint
{
public:
    virtual void process(int value) =0;
    virtual void process(double value) =0;
    virtual ~Iprint(){}
};

class Print : public Iprint
{
public:
    Print()
    {
        cout<<"this is Print() construct"<
    void PrintArray(T value);
};

template void Print:: PrintArray(T value)
{
    cout<<"PrintArray value:"<process(10);
	p->process(20.0);

	return 0;
}
二,泛化类

主要用于:不同的类,相同的成员函数/成员变量等,可以用template封装成一个对象。
有些情况和工厂模式类似。

实例:

template
class Print
{
public:
    Print()
    {
        cout<<"this is Print() construct"< print1;
	print1.printType();
    cout<<"***************************************"< print2;
	print2.printType();
	return 0;
}
三,常见的问题 1,Missing template arguments before '.' token

原因:若类里包含template模板,该类实例时,不清楚对应的T是什么类型。
方案一:实例化时时指定类型,e.g:A a;
方案一:可以用虚基类的方式,在派生类的方法里使用template

2, error: ‘T’ was not declared in this scope

原因:T没有声明
方案:在定义和声明时都加:template

四,Typename由来

"typename"是一个C++程序设计语言中的关键字。相当用于泛型编程时是另一术语"class"的同义词。这个关键字用于指出模板声明(或定义)中的依赖的名称(dependent names)是类型名,而非变量名。

很多情况下typename和class用法一样

个人建议:typename用于基本类型,class用于class类型

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/968372.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号