C++ - 非类型模板参数(nontype template parameters) 使用 及 代码

来源:互联网 发布:04年总决赛科比数据 编辑:程序博客网 时间:2024/05/29 04:25

非类型模板参数(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

下面例子包含了模板类型是 整型, 指针, 引用, 函数指针 的函数的常见写法;

注意指针和引用的实参是全局变量;

代码如下:

[cpp] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. //=====================================  
  2. // Name        : CppPrimer.cpp  
  3. // Author      : Caroline  
  4. // Version     : 1.0  
  5. // Description : Example, UTF-8  
  6. //=====================================  
  7.   
  8. /*eclipse cdt, gcc 4.8.1*/  
  9.   
  10. #include <iostream>  
  11. #include <vector>  
  12. #include <cstring>  
  13.   
  14. using namespace std;  
  15.   
  16. //整型模板  
  17. template<unsigned N, unsigned M>  
  18. bool compare (const char (&p1)[N], const char (&p2)[M])  
  19. {  
  20.     std::cout << "size : " << N << " " << M << std::endl;  
  21.     return strcmp(p1, p2);  
  22. }  
  23.   
  24. //指针  
  25. template<const char* C>  
  26. void pointerT(const char* str){  
  27.     std::cout << C << " " << str << std::endl;  
  28. }  
  29.   
  30. //引用  
  31. template<char (&ra)[9]>  
  32. void referenceT(const char* str){  
  33.     std::cout << ra << " " << str << std::endl;  
  34. }  
  35.   
  36. char ca[] = "Caroline"//初始化指针  
  37. char cr[9] = "Caroline"//初始化引用, 包含一个结尾符号  
  38.   
  39. void f(const char* c) {std::cout << c << std::endl; }  
  40.   
  41. //函数指针  
  42. template<void (*F)(const char*)>  
  43. void fpointerT(const char* c) {  
  44.     F(c);  
  45. }  
  46.   
  47. int main(void)  
  48. {  
  49.     if(compare("Caroline""Wendy")) {  
  50.         std::cout << "Caroline is long." << std::endl;  
  51.     } else {  
  52.         std::cout << "Wendy is long." << std::endl;  
  53.     }  
  54.   
  55.     //无法使用局部变量或者动态变量作为模板参数  
  56.     pointerT<ca>("Wendy"); //指针  
  57.   
  58.     referenceT<cr>("Wendy"); //引用  
  59.   
  60.     fpointerT<f>("Caroline Wendy"); //函数指针  
  61.   
  62.     return 0;  
  63. }  

输出:

[cpp] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. size : 9 6  
  2. Caroline is long.  
  3. Caroline Wendy  
  4. Caroline Wendy  
  5. Caroline Wendy  
0 0
原创粉丝点击