3,882
社区成员
发帖
与我相关
我的任务
分享
template <int a,int b>
int add (){
return a+b;
};
const int& n=3;
add<n,4>();
8.2.2 Nontype Parameters
Nontype template parameters stand for constant values that can be determined at compile or link time. The type of such a parameter (in other words, the type of the value for which it stands) must be one of the following:
Template template parameters do not denote types either; however, they are not considered when talking about nontype parameters.
An integer type or an enumeration type
A pointer type (including regular object pointer types, function pointer types, and pointer-to-member types)
A reference type (both references to objects and references to functions are acceptable)
引用类型是可以的呢,上面说了,对象的引用和函数引用都可以啊。
template <int &N>
struct _Ref
{
int getValue() {return N;}
};
template <int N>
struct _Val
{
int getValue() {return N;}
};
int global_a; // 全局变量默认为0
int const global_b = 1;
int main ()
{
_Ref<global_a> instance1; // OK 引用类型必须是全局的
_Val<global_b> instance2; // OK 值类型必须是编译期常量
std::cout << instance1.getValue() << std::endl;
std::cout << instance2.getValue() << std::endl;
}