类的模板函数

关于c++的类的模板函数和c++调用cuda的模板函数的一些注意事项

c++
类成员模板函数实现不能再cpp里面,一般是放在.hpp里面,外部调用时候直接引入该头文件

.h文件的模板函数
#ifndef CNNSTONEREC
#define CNNSTONEREC


class BaseCnnStoneRec
{
public:
    BaseCnnStoneRec() {};
    BaseCnnStoneRec(std::string modelName, std::string deepNetName);
    ~BaseCnnStoneRec() ;

public:

    template<typename T>
    void RecStones(T *int_data_input_device, unsigned int stoneNum);

}
#endif
#include"CnnStoneRec.hpp"

.hpp实现
#pragma once
template<typename T>
void BaseCnnStoneRec::RecStones(T*int_data_input_device, unsigned int stoneNum) {
    loadImage(int_data_input_device, stoneNum);
    RecStones();
}
template<typename T>
inline void BaseCnnStoneRec::loadImage(T * int_data_input_device, unsigned int stoneNum)
{
    m_gpuImage.stoneNum = stoneNum;
    m_gpuImage.length = stoneNum * m_gpuImage.resize_x * m_gpuImage.resize_y * m_gpuImage.channels;
    float div = 1.0;

    if (std::is_same<T, uchar>::value)
        div = 1.0;
    else if (std::is_same<T, unsigned short>::value)
        div = 256.0;
    data2float(int_data_input_device, m_gpuImage.length, \
        div, m_gpuImage.mean, m_gpuImage.scale, m_gpuImage.resize_x, \
        m_gpuImage.channels, m_gpuImage.datas_device);

}
cuda的模板函数
关于cuda的模板函数一般暴露给外部的cpp文件是一个c语言模板函数 例如.hpp文件中的data2float函数 ,如果直接在里面调用cuda核函数的时候,通过外部调用会出现未定义的函数,这时候需要实例化模板函数

.cu文件中的data2float函数写法如下
template<class T>
void data2float(T *data_d_R, unsigned int len, float div, float mean, float scale, int resize_size, int channel, float* out)
{
    //输入图像数据16int转浮点并归一化,一个线程转一个。
    //最大的线程数应该大于输入图像的大小,即(石头个数*96*96)。
    // 128*128*32*32/96/96=1820   已经足够了。
    dim3 gridsize(128, 128);
    dim3 blocksize(32, 32);
    convertToFloatTypeKernel<T><<< gridsize, blocksize >>> (data_d_R, len, resize_size, channel, div, mean, scale, out);

}
//下面的两个函数是一个实例化
template void
data2float<unsigned char>(unsigned char *data_d_R, unsigned int len, float div, \
    float mean, float scale, int resize_size, int channel, float* out);
template void
data2float<unsigned short>(unsigned short *data_d_R, unsigned int len, float div, \
    float mean, float scale, int resize_size, int channel, float* out);

关于convertToFloatTypeKernel核函数的实现
template <class T>
__global__ void 
convertToFloatTypeKernel(T *inputdata, unsigned int len, int resize_size, int channel, float div, float mean, float scale, float* out)
{
    代码部分暂时不开放
}

 


总结:关于c++的类成员模板函数是通过hpp中来实现,调用cuda的模板函数 需要在cu里进行实例化

欢迎在下方留下您的问题,也可以咨询我的qq247932449

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值