2012-02-01 65 views
0

我只是想知道为什么我应该让我传递给函数模板的变量必须是const?为什么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,那么我会得到一个错误“未初始化的数组”。

任何人都可以请让我知道,如果这是发送到函数模板的参数必须是常量类型的规则?

回答

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++允许。

相关问题