您的位置:首页 > 其它

template non-type parameter 非类型参数

2015-03-31 16:44 447 查看
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



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: