template non-type parameter 非类型参数

本文探讨了在C++中使用整数作为模板参数的灵活性与实用性,通过实例展示了如何在编译时计算阶乘并创建矢量结构。

CUDA v6.5 sample->0_simple->matrixMul 中看到语法:

template <int BLOCK_SIZE> __global__ void
matrixMulCUDA(float *C, float *A, float *B, int wA, int wB)
{
    // function body
}

对于用法:

template <typename \ class>


是很常见的,但对于用法:

template <int >


却少见。


It's perfectly possible to template a class on an integer rather than a type. We can assign the templated value to a variable, or otherwise manipulate in a way we might with any other integer literal:

unsigned int x = N;


In fact, we can create algorithms which evaluate at compile time (from Wikipedia):

template <int N>
struct Factorial 
{
     enum { value = N * Factorial<N - 1>::value };
};

template <>
struct Factorial<0> 
{
    enum { value = 1 };
};

// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
    int x = Factorial<4>::value; // == 24
    int y = Factorial<0>::value; // == 1
}

使用 int 类型模板,可以在编译时确定。例如:

template<unsigned int S>
struct Vector {
    unsigned char bytes[S];
};

// pass 3 as argument.
Vector<3> test;


更多内容可参考: http://stackoverflow.com/questions/499106/what-does-template-unsigned-int-n-mean

http://stackoverflow.com/questions/24790287/templates-int-t-c



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值