2011-11-22 19 views
5

मैं निम्नलिखित कोड है:टेम्पलेट संकलन त्रुटि - मानक या नहीं?

template<int k> 
void foo() 
{ 
} 
int main(int argc, char* argv[]) 
{ 
    int k = 1000; 
    foo<k>(); 
    return 0; 
} 

जो संकलन नहीं है, लेकिन अगर मैं const रूप k घोषित, यह करता है:

template<int k> 
void foo() 
{ 
} 
int main(int argc, char* argv[]) 
{ 
    const int k = 1000; 
    foo<k>(); 
    return 0; 
} 

अब, मैं पीछे तर्क क्यों पहले में अगर यह संकलित नहीं होता है और दूसरे में यह करता है, लेकिन क्या यह मानक द्वारा निर्दिष्ट है?

त्रुटि मैं हो रही है:

Error 1 error C2971: 'foo' : template parameter 'k' : 'k' : a local variable cannot be used as a non-type argument 

जो वास्तव में स्पष्ट नहीं है, के बाद से k एक स्थानीय चर मामला यह const है में भी है ... है ना?

error: ‘k’ cannot appear in a constant-expression

उत्तर

2

§14.3.2.1 का कहना है के रूप में वेरिएबल का संदर्भ सेट कर सकते हैं [संक्षिप्त]:

A template-argument for a non-type, non-template template-parameter shall be one of:
— an integral constant-expression of integral or enumeration type;

और §5.19 .1 कहते हैं [संक्षिप्त, जोर मेरा]:

An integral constant-expression can involve only literals, enumerators, const variables or static data members of integral or enumeration types initialized with constant expressions...

k संतुष्ट इस की दूसरी परिभाषा, तो यह टेम्पलेट तर्क के लिए एक बर्फ के रूप में इस्तेमाल किया जा करने की अनुमति दी है।

त्रुटि उस में थोड़ा भ्रामक है कि "एक स्थानीय चर को गैर-प्रकार तर्क के रूप में उपयोग नहीं किया जा सकता है" सामान्य सामान्य में है, लेकिन कुछ प्रतिबंधों के साथ यह बिल्कुल ठीक है।

4

मानक, 14.3.2 के अनुसार, इस एक निरंतर अभिव्यक्ति होना चाहिए संकलन समय पर मूल्यांकन किया गया जब संकलक टेम्पलेट को अंतिम रूप में विस्तारित करने का प्रयास करता है। तो निष्पादन समय मूल्यों टेम्पलेट्स के लिए तर्क नहीं किया जा सकता है, लेकिन हमेशा आप टेम्पलेट तर्क

template<int& k> 
void foo() 
{ 
} 
int main(int argc, char* argv[]) 
{ 
    int k = 1000; 
    foo<k>(); 
    return 0; 
} 
+0

आपने यह निर्दिष्ट नहीं किया कि क्यों 'के' एक में काम करता है लेकिन दूसरा नहीं, जो प्रश्न का मांस था। – GManNickG

+0

मैंने जो अनुभाग बोल्ड किया है उसे देखें। मानक कहता है कि अभिव्यक्ति निरंतर होना चाहिए। –

+0

लेकिन मैं खुद को दोहराता हूं: आप यह नहीं पता कि क्यों 'के' प्रयोग योग्य है या नहीं। – GManNickG

2

सं कॉन्स्ट मूल्यों हो सकता है:

A template-argument for a non-type, non-template template-parameter shall be one of:
an integral constant-expression of integral or enumeration type; or
— the name of a non-type template-parameter; or
— the address of an object or function with external linkage, including function templates and function template-ids but excluding non-static class members, expressed as & id-expression where the & is optional if the name refers to a function or array, or if the corresponding template-parameter is a reference; or
— a pointer to member expressed as described in 5.3.1 .

जीसीसी 4.6.2 एक से थोड़ा अधिक सुबोध त्रुटि देता है:

संबंधित मुद्दे