c++ - 为什么 const 关键字对于定义模板参数是强制性的?

标签 c++ function templates

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

例子:-

   #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 类型的规则吗?

最佳答案

我只是想知道为什么我要让我传递给函数模板的变量必须是常量?
不,你不需要,问题出在别处。

在 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++ 中是不允许的。

关于c++ - 为什么 const 关键字对于定义模板参数是强制性的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9092151/

相关文章:

actionscript-3 - 在 AS3 中在运行时(反射)检查匿名函数签名

javascript - 无法在 Js 函数中将 HTML Collection 作为参数传递?

mysql - MediaWiki:调用模板、ParserFunctions 条件取决于外部数据值

silverlight - 将模板属性值绑定(bind)到模板化控件属性

c++ - <algorithm> 是否定义了宏 X?

C++ 三元运算符字符串连接

java - Java 8 中的谓词和函数接口(interface)有什么区别?

c++ - 成员类型模板特化

c++ - 使用不完整类型的函数模板实例化

c++ - 为什么 SetMenuInfo 在 Windows 7 下不起作用?