• template关键字


    概念:用于泛型编程,当某个算法或者数据结构与数据无关,其中的元素可以是任意一种类型时,可以使用泛型来解决代码重复定义的问题,使用template关键字定义模板函数或者模板类的数据类型,在编译时,编译器会用具体的数据类型来替换占位符。

    注意:模板的声明或定义只能在全局,命名空间或类范围内进行。即不能在局部范围,函数内进行。

    定义:

    template <类型名 占位符>
    //不确定参数个数的模板定义  
    template <类型名... 占位符 >
    
    • 1
    • 2
    • 3

    类型名可以通过typeid(类型名)获取类型ID来判断参数是否为某种类型如:
    if(typeif(类型名) == typeid(uint_32)) 来判断类型是不是uint_32类型

    模板类
    格式:

    template <[class | typename] 形参名称, [class | typename]  形参名称, ....>  
    class 类名
    {
        <函数体>
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    实例:

    template<class T, typename D>
    class DemoClass{
    public:
        T t;
        D d;
        void addBySelf(){
            ALOGE(" define string is %s ", typeid(uint8_t).name());
            ALOGE(" define string is %s ", typeid(D).name());
            ALOGE(" define typename is %s ", typeid(T).name());
    
            if(typeid(D).name() == typeid(std::string).name()){
                std::string val = static_cast<std::string>(d);
                ALOGE(" D VALUE IS %s", val.c_str());
            }
    
            if(typeid(uint8_t).name() == typeid(T).name()){
                ALOGE("==========> TRUE");
            }
        }
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    模板函数

    template<class A>
    A add(A a, A b){
        return a + b;
    }
    
    • 1
    • 2
    • 3
    • 4

    模板可变参数

    template<typename F, typename... Arg>
    void getArgs(const F& f, Arg&&... args) {
        std::initializer_list<int>({(f(std::forward<Arg>(args)), 0)...});
    }
    
    • 1
    • 2
    • 3
    • 4
    getArgs([](int i){ALOGE("%d", i);}, 1, 2,3,4,5);
    //输出: 1,2,3,4,5
    
    • 1
    • 2
  • 相关阅读:
    android app开发环境搭建
    [附源码]计算机毕业设计JAVA卡牌交易网站
    云数一体机
    SpringCloud
    Shell脚本练习——系统应用相关(2)
    uniapp-从后台返回的一串地址信息上,提取省市区进行赋值
    Syncfusion Essential Studio 23.2.4 V3 SP1 Crack
    Vue 3 快速上手指南(第二期)
    git强制覆盖本地命令
    痞子衡嵌入式:聊聊系统看门狗WDOG1在i.MXRT1xxx系统启动中的应用及影响
  • 原文地址:https://blog.csdn.net/zjfengdou30/article/details/126165046