我发现Johannes Schaub - litb 的this answer 对另一个问题很有帮助。
[ 我在这里复制粘贴答案,假设 Johannes 没问题。如果他不喜欢,我会删除粘贴 ]
是的,它是一个非类型参数。你可以有几种模板参数
你所拥有的是最后一种。它是一个编译时常量(所谓的常量表达式),并且是整数或枚举类型。在标准中查找之后,我不得不将类模板上移到类型部分——即使模板不是类型。但是为了描述这些类型,它们被称为类型参数。您可以拥有指针(以及成员指针)和对具有外部链接的对象/函数的引用(可以从其他目标文件链接到并且其地址在整个程序中是唯一的)。例子:
模板类型参数:
template<typename T>
struct Container {
T t;
};
// pass type "long" as argument.
Container<long> test;
模板整数参数:
template<unsigned int S>
struct Vector {
unsigned char bytes[S];
};
// pass 3 as argument.
Vector<3> test;
模板指针参数(将指针传递给函数)
template<void (*F)()>
struct FunctionWrapper {
static void call_it() { F(); }
};
// pass address of function do_it as argument.
void do_it() { }
FunctionWrapper<&do_it> test;
模板引用参数(传递整数)
template<int &A>
struct SillyExample {
static void do_it() { A = 10; }
};
// pass flag as argument
int flag;
SillyExample<flag> test;
模板模板参数。
template<template<typename T> class AllocatePolicy>
struct Pool {
void allocate(size_t n) {
int *p = AllocatePolicy<int>::allocate(n);
}
};
// pass the template "allocator" as argument.
template<typename T>
struct allocator { static T * allocate(size_t n) { return 0; } };
Pool<allocator> test;
没有任何参数的模板是不可能的。但是没有任何显式参数的模板是可能的 - 它具有默认参数:
template<unsigned int SIZE = 3>
struct Vector {
unsigned char buffer[SIZE];
};
Vector<> test;
在语法上,template<> 保留用于标记显式模板特化,而不是没有参数的模板:
template<>
struct Vector<3> {
// alternative definition for SIZE == 3
};