---
title: "c++无类型参数模板(non-type template parameter)  与 无具名空间 static"
author: "fujinbing"
date: "2013-04-20T15:19:52Z"
tags: []
categories: ["编程语言"]
slug: "c-non-type-template-parameter-static"
draft: false
lastmod: "2013-04-20T15:22:02Z"
id: 1850722
url: "https://fujinbing.iteye.com/blog/1850722"
---

无类型的模板参数：

     C++的template可以传入普通的参数，和平时使用普通的函数参数有点相似，但又有很大的不同。  
    这种形式的模板一般是用来初始化类的数组成员的大小例如下面有的代码：

     template&lt;int size&gt;  
     class CTest {  
         int m\_data\[size];  
     };  
    void main() {  
        CTest&lt;10&gt; obj;// 将obj对象的成员 数值m\_data大小初始为10 ，是不是很简单？  
     }

     用整型来作为无类型模板参数使用起来确实simple，那么换其他类型试试？

     收集了一点资料稍微整理了下，看看下面资料怎么说的：  
      a non-type template-parameter shall have one of the following types

      (无类型模板参数应该是下面所列举的类型):  
     1. integral or enumeration type（整型 或者 枚举）  
     2. pointer to object or pointer to function（对象的指针或函数指针,其实还包括基本类型的指针）  
     3. reference to object or reference to function（对象的引用或者函数的引用）  
     4. Attention ：The C++ standard does not allow floating point non-type template parameters  
   （注意：c++标准规定浮点型不能作为无类型模板的参数，但他们的引用和指针是允许的。例如 float，double）

   **你已经知道了应该传入什么类型参数，说真的，这还远远不够。**  
   a template-argument for a non-type, non-type template-parameter shall be one of：  
     1.对于整型参数：应该传入一个常量或者枚举值  
       an integral constant-expression of integral or enumeration type  
     2.对象的指针或者函数的地址因该具有外部连接属性，具有内部链接属性将报错;

       the address of an object or function with external linkage  
     3.可以是一个引用类型的参数参数 例如: template&lt;int&&gt; void func() {};   
       the corresponding template-parameter is a reference

 

     **下面再来看看non-type template-parameter 有关的错误描述：**  
      error c2970:   
      an expression involving objects with internal linkage cannot be used as a non-type argument

     （涉及到对象内部连接的表达式不能作为 non-type argument）

      error c2975:  
      expected compile-time constant expression

      (需要一个编译期常量表达式)

      error c2971:  
      a local variable cannot be used as a non-type argument,

      You cannot use the name or address of a local variable as a template argument.

    （局部变量不能作为non-type argument,

        这里主要是指：指针和引用，但是局部整型常量除外，所以下面的代码是ok的。

 

 

01. template&lt;int&gt;
02. void fun1()     {}
03. template&lt;int\*&gt;
04. void fun1\_1()   {}
05. template&lt;int&&gt;
06. void fun1\_2()   {}
07. template&lt;char\*&gt;
08. void fun2()     {}
09. template&lt;char&gt;
10. void fun3()     {}
11. struct  CA  {};
12. union   Ua  {};
13. // 浮点数 例如float,double，是不能作为 non-type template parameter的
14. //template&lt;float&gt;
15. //void fun4()   {}
16. // 要使用类的或者联合的指针 或者引用
17. //template&lt;CA&gt;
18. //void fun4()   {}
19. //template&lt;Ua&gt;
20. //void fun5()   {}
21. template&lt;CA\*&gt;
22. void fun4\_1()   {}
23. template&lt;CA&&gt;
24. void fun4\_2()   {}
25. template&lt;Ua\*&gt;
26. void fun5\_1()   {}
27. template&lt;Ua&&gt;
28. void fun5\_2()   {}
29. //------------------------------------------------------------------------//
30. int         idata3 = 20;        // 外部链接
31. const int   idata2 = 9;         // 内部链接
32. CA          impCa1;             // 外部链接
33. const CA    impCa2;             // 内部链接
34. static CA   impCa3;             // 内部链接
35. Ua          impUa1;             // 外部链接
36. const Ua    impUa2;             // 内部链接
37. static Ua   impUa3;             // 内部链接
38. const char  str3\[] = "str";     // 内部链接
39. static char str4\[] = "str";     // 内部链接
40. char        str5\[] = "str";     // 外部链接
41. char*       str6   = "str";     // 外部链接
42. const char* str7   = "str";     // 内部链接
43. char* const str8   = "str";     // 内部链接
44. const char* const str9   = "str";   // 内部链接
45. const char  chr    = 'x';       // 内部链接
46. void funtest(int);
47. void funtest( int )     {}
48. static void funtest2(int);
49. void funtest2( int )    {}
50. typedef void (\*ptr\_func)(int);
51. template&lt;ptr\_func&gt;
52. void fun6()     {}
53. ptr\_func pfun2 = &funtest;
54. const ptr\_func pfun3 = &funtest;
55. static const ptr\_func pfun4 = &funtest;
56. int \_tmain(int argc, \_TCHAR* argv\[])
57. {
58. int i = 12;
59. //const int idata = i;  // error 2971 局部变量不能用作非类型参数
60. const int idata = 10;   // 局部常量 ok
61. fun1&lt;idata&gt;();            // ok
62. int idata4 = 20;
63. //fun1\_1&lt;&idata2&gt;();  // error c2970 涉及到对象内部连接的表达式不能作为 non-type argument.
64. //fun1\_1&lt;&idata4&gt;();  // error c2971
65. fun1\_1&lt;&idata3&gt;();        // ok
66. //fun1\_2&lt;idata2&gt;();       // error c2970
67. //fun1\_2&lt;idata4&gt;();       // error c2971
68. fun1\_2&lt;idata3&gt;();     // ok
69. char        str1\[]  = "string";
70. const char* str2    = "string";
71. //fun2&lt;str1&gt;();           // error c2971
72. //fun2&lt;str2&gt;();           // error c2971
73. //fun2&lt;str3&gt;();           // error c2970
74. //fun2&lt;str4&gt;();           // error c2970
75. //fun2&lt;"test"&gt;();     // error c2762 模板参数的表达式无效,为什么会无效？字符串"test"具有内部链接? 问题1。
76. fun2&lt;str5&gt;();         // ok
77. //fun2&lt;str6&gt;();           // error 2975 需要一个编译期常量表达式
78. //fun2&lt;str7&gt;();           // error 2975
79. //fun2&lt;str8&gt;();           // error c2971
80. //fun2&lt;str9&gt;();           // error c2971
81. //fun3&lt;str2\[1]&gt;();        // error 2975 需要一个编译期常量表达式
82. //fun3&lt;str3\[0]&gt;();        // error 2975 为什么str3\[0]不是编译期常量，问题2
83. fun3&lt;'x'&gt;();          // ok
84. fun3&lt;chr&gt;();          // ok
85. // ok
86. fun4\_1&lt;&impCa1&gt;();
87. fun4\_2&lt;impCa1&gt;();
88. // ok
89. fun5\_1&lt;&impUa1&gt;();
90. fun5\_2&lt;impUa1&gt;();
91. //
92. ptr\_func pfun = &funtest;
93. //fun6&lt;pfun&gt;();       // error c2971
94. //fun6&lt;pfun2&gt;();  // error c2975
95. //fun6&lt;pfun3&gt;();  // error C2970
96. //fun6&lt;&pfun4&gt;(); // error C2970
97. fun6&lt;&funtest&gt;(); // ok
98. fun6&lt;&funtest2&gt;();
99. return 0;

 

## [**C++** **中** **static** 和 **anonymouse** **namespace** **的差别**](http://www.alisdn.com/wordpress/?p=879 "链接到C++ 中 static 和 anonymouse namespace 的差别")

2009-01-02 14:54  |  分类：[桌面应用开发](http://www.alisdn.com/wordpress/?cat=38 "显示桌面应用开发的所有日志")

记得以前一个同事问我为什么程序里使用了 **anonymouse** **namespace** ，想了想 就回答说其实就是保持局部性（这也是我的目的），然后就有人说为什么不用**static**，嗯 似乎这两个东西乍一看没什么区别，自己便Google了一下，发现有一个原因就是 anonymousenamespace 里的 member 都是有外部链接的，只不过永远都不能被外部link到！而 **static** 就明确为根本没有外部链接！此时就出现问题了，在模板里无类型的参数必须是有外部链接的才可以，否则编译无法通；比如：  
template &lt;void fn()&gt;  
class Foobar  
{};

**namespace**  
{  
void abc()  
{  
wcout&lt;&lt;\_T(”abc”)&lt;&lt;endl;  
};  
}  
**static** void efg()  
{  
wcout&lt;&lt;\_T(”efg”)&lt;&lt;endl;  
};  
int \_tmain(int argc, \_TCHAR* argv\[])  
{  
Foobar&lt;abc&gt;xyz //! ;这一行可以通过  
Foobar&lt;efg&gt;rst; //! 注意这一行编译不过  
return 0;  
}  
也有人认为使用 anon **namespace**比较好，因为**static**的方式被C++98标准所批评，呵呵 总体来说 ，其实你完全可以用anony **namespace**代替**static**。