为什么const关键字对于定义模板参数是必需的?

时间:2012-02-01 07:11:05

标签: c++ function templates

我只是想知道为什么我要传递给函数模板的变量必须是const?

例如: -

   #include <iostream>
   using std::cout;
   using std::endl;

   template< typename T>
   void printArray( T *array, int count )
   {
      for ( int i = 0; i < count; i++ )
         cout << array[ i ] << " ";
      cout << endl;
   }

   int main()
   {
     const int ACOUNT = 5; // size of array a
     const int BCOUNT = 7; // size of array b
     const int CCOUNT = 6; // size of array c

     int a[ ACOUNT ] = { 1, 2, 3, 4, 5 };
     double b[ BCOUNT ] = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
     char c[ CCOUNT ] = "HELLO"; // 6th position for null

     cout << "Array a contains:" << endl;

     // call integer function-template specialization
     printArray( a, ACOUNT );

     cout << "Array b contains:" << endl;

     // call double function-template specialization
     printArray( b, BCOUNT );

     cout << "Array c contains:" << endl;

     // call character function-template specialization
     printArray( c, CCOUNT );
     return 0;
   }

这里主要功能: - 我声明了变量

 const int ACOUNT = 5; // size of array a
 const int BCOUNT = 7; // size of array b
 const int CCOUNT = 6; // size of array c

const。如果我不将它们声明为const,那么我会收到错误“未初始化的数组”。

任何人都可以告诉我,如果这是发送到函数模板的参数必须是const类型的规则吗?

1 个答案:

答案 0 :(得分:4)

我只是想知道为什么我要传递给函数模板的变量必须是const?
不,你不需要,问题出在其他地方。

在C ++中,您不能拥有 Variable Length Arrays(VLA) 因此,声明数组时,应将长度声明为编译时常量。

const  int ACOUNT = 5; // size of array a
const int BCOUNT = 7; // size of array b
const int CCOUNT = 6; // size of array c

int a[ ACOUNT ] = { 1, 2, 3, 4, 5 };
double b[ BCOUNT ] = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
char c[ CCOUNT ] = "HELLO"; // 6th position for null

在上面的示例中,如果没有const,您的数组将被声明为VLA,而C ++中不允许这样做。