2012-02-01 7 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として

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++で許可されていません。

関連する問題