非类型模板参数(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
下面例子包含了模板类型是 整型, 指针, 引用, 函数指针 的函数的常见写法;
注意指针和引用的实参是全局变量;
代码如下:
-
-
-
-
-
-
-
-
-
- #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