非类型模板参数(nontype template parameters) 使用 及 代码
本文地址: http://blog.csdn.net/caroline_wendy/article/details/17219921
非类型模板参数(nontype template parameters), 可以使用整型类型(integral type),指针(pointer) 或者是 引用(reference);
绑定非类型整数形参(nontype integral parameter) 的 实参(argument) 必须是常量表达式(constant expression, constexpr);
不能把普通的局部对象或者动态对象 绑定 指针或引用的非类型形参, 可以使用全局类型进行绑定;
关于类模板(class template)中非类型模板参数的写法,参见: http://en.cppreference.com/w/cpp/language/class_template
下面例子包含了模板类型是 整型, 指针, 引用, 函数指针 的函数的常见写法;
注意指针和引用的实参是全局变量;
代码如下:
//=====================================
// Name : CppPrimer.cpp
// Author : Caroline
// Version : 1.0
// Description : Example, UTF-8
//=====================================
/*eclipse cdt, gcc 4.8.1*/
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
//整型模板
template<unsigned N, unsigned M>
bool compare (const char (&p1)[N], const char (&p2)[M])
{
std::cout << "size : " << N << " " << M << std::endl;
return strcmp(p1, p2);
}
//指针
template<const char* C>
void pointerT(const char* str){
std::cout << C << " " << str << std::endl;
}
//引用
template<char (&ra)[9]>
void referenceT(const char* str){
std::cout << ra << " " << str << std::endl;
}
char ca[] = "Caroline"; //初始化指针
char cr[9] = "Caroline"; //初始化引用, 包含一个结尾符号
void f(const char* c) {std::cout << c << std::endl; }
//函数指针
template<void (*F)(const char*)>
void fpointerT(const char* c) {
F(c);
}
int main(void)
{
if(compare("Caroline", "Wendy")) {
std::cout << "Caroline is long." << std::endl;
} else {
std::cout << "Wendy is long." << std::endl;
}
//无法使用局部变量或者动态变量作为模板参数
pointerT<ca>("Wendy"); //指针
referenceT<cr>("Wendy"); //引用
fpointerT<f>("Caroline Wendy"); //函数指针
return 0;
}
输出:
size : 9 6
Caroline is long.
Caroline Wendy
Caroline Wendy
Caroline Wendy