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

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

被折叠的 条评论
为什么被折叠?



