C++/ cuda kernel中的模版元编程识别 kernel 模版的数据类型

1,模版元编程

模板元编程是一种利用 C++ 模板系统在编译时进行计算和生成代码的技术。其原理基于模板特化、递归、模板参数推导等特性,通过模板实例化和展开,在编译时生成代码,以实现在编译期间进行复杂计算和代码生成的目的。

2,模版元编程的典型示例

编译期间展开计算出斐波那契数列的具体数值:

需要特化0和1的情况,

mo.cpp

#include <iostream>

template <int N>
struct Fibonacci {
    static const int value = Fibonacci<N - 1>::value + Fibonacci<N - 2>::value;
};

template <>
struct Fibonacci<0> {
    static const int value = 0;
};

template <>
struct Fibonacci<1> {
    static const int value = 1;
};

int main() {
    const int result = Fibonacci<10>::value;
    std::cout << "Fibonacci(10) = " << result << std::endl;
    return 0;
}

3,CUDA kernel中实践模版元编程

示例代码

hello.cu

#include <stdio.h>

template <typename T, typename U>
struct IsSame {
    static const bool value = false;
};

template <typename T>
struct IsSame<T, T> {
    static const bool value = true;
};

template <typename T>
__global__ void checkTypes() {
    if (IsSame<T, int8_t>::value) {
        printf("t s the same type ssssss");
    } else {
        printf("t d not the same type dddddd\n");
    }
}

int main() {
    checkTypes<int><<<1, 1>>>();
    cudaDeviceSynchronize();
    return 0;
}

这时只会将 dddddd编译进去,类型不同;

nvcc hello.cu

故vim a.out

查找dddddd和ssssss:

dddddd找到了

ssssss没找到:

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值