c++模板杂谈

实验环境 linux mint 下 Qt 5.11

说白了,模板就是搭个函数,类的框架,具体实现的时候往里面填充内容,或者我们可以把类型名想作一个占位符号

  • 函数模板----俗气的比大小
#include <iostream>
#include<string.h>
using namespace std;


template <class TYPE>
TYPE returnmax(TYPE x, TYPE y)
{
    return (x>y)?x:y;
}

char*  returnmax(char* x,char* y)
{
    return (strcmp(x,y)<0)?x:y;
}


int main()
{
    cout << "Hello World!" << endl;
    char* chorum2 ="你你你你要跳舞吗";
    char* chorum1 ="每当浪潮来临的时候,你会不会也伤心";
    cout<<returnmax(chorum1,chorum2)<<endl;
    cout<<returnmax(99,888)<<endl;
    return 0;
}

输出结果:

c++模板杂谈

  •  类模板---使数据结构和算法不受所包含的元素类型的影响

目录结构

c++模板杂谈

 

  •  头文件
#ifndef XA_H
#define XA_H
#include<iostream>
#include<string.h>
using namespace std;

template <class sometype>
class xa
{
public:
    xa(sometype x)
    {
        myx = x;
    }
    void showme()
    {
        cout<<this->myx<<endl;
    }
private:
    sometype myx;
};

#endif // XA_H
  • 具体调用
#include <iostream>

using namespace std;
#include "xa.h"
int main()
{
    xa<char*> myx("瑞典鹰狮战斗机");
    myx.showme();
    xa<int> another(888);
    another.showme();

    //cout << "Hello World!" << endl;
    return 0;
}

输出结果:

c++模板杂谈

  • 一个类模板的定义与实现 主要特征是构造函数参数列表中第一个参数可能是字符指针或者整型数

项目构成

c++模板杂谈

 

    •  
  • mytempl.h

#ifndef MYTEMPL_H
#define MYTEMPL_H

template <class wenwa>
class mytempl
{
public:
    mytempl(wenwa name,int age);
    wenwa name;
    int age;
    void showme();
};

#endif // MYTEMPL_H
  • mytempl.cpp

#include "mytempl.h"
#include <iostream>
using namespace std;
template <class wenwa>
mytempl<wenwa>::mytempl(wenwa name,int age)
{
    this->name=name;
    this->age=age;
}

template <class wenwa>
void mytempl<wenwa>::showme()
{
    if(typeid(wenwa)==typeid(int))
    {
            cout<<"哇哒吸袜~三井重工"<<this->name<<"号防卫机器人"<<endl;
            cout<<"武器装备:"<<this->age<<"毫米火炮"<<endl;
    }
    else
    {
        cout<<"大家好!我是 "<<this->name<<endl;
        cout<<"那什么尺寸:"<<this->age<<"cm"<<endl;
    }
}
  • main.cpp

#include <iostream>
#include "mytempl.cpp"

using namespace std;

int main()
{
    mytempl<int> robot(888,120);
    robot.showme();
    cout<<" ......."<<endl;
    mytempl<char*> cpc("昌仔",22);
    cpc.showme();
    return 0;
}

输出结果:

c++模板杂谈

 

原文链接: https://www.cnblogs.com/saintdingspage/p/12247418.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    c++模板杂谈

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/326361

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午3:47
下一篇 2023年3月1日 下午3:47

相关推荐