模板函数举例

1、

在includes.h中定义,应该是全局函数,作用是打印入参:

template<typename T>
void record(T info)
{
    qDebug()<<info;
}

可根据不同平台修改打印函数,这里是Qt平台,使用的是qDebug,也可以C++的std::cout

使用:

record<int>(1);//先包含头文件

 2、类内部的函数模板

template<class T>//获取服务,通过模板
T* getService()
{
    qDebug()<<"getService";
    T* s;
    RET_VALUE_IF_EAQU(context,nullptr,s);
    ctkServiceReference reference = context->getServiceReference<T>();
    if(reference)
    {
        s = context->getService<T>(reference);// 获取指定 ctkServiceReference 引用的服务对象
        if (s == nullptr)
        {
            print("Try to get a invalid service");
        }
    }
    return s;
}

使用

AbsLogService* log = PullService::getInstance()->getService<AbsLogService>();
log->log("123");

 

ps:

最好函数的声明和定义都在头文件中完成,如果分开有如下两个问题:

①、警告

warning: instantiation of function' required here, but no definition is available

②、运行报错

无法解析的外部符号 xxxx,该符号在函数 main 中被引用

posted @ 2019-10-09 11:55  朱小勇  阅读(492)  评论(0编辑  收藏  举报