2011-02-11 17 views
11

में टेम्पलेट फ़ंक्शन में पॉइंटर के साथ त्रुटि संकलित करें मैं एक टेम्पलेट क्लास बनाने की कोशिश कर रहा हूं जो टेम्पलेट फ़ंक्शन पर फ़ंक्शन पॉइंटर संग्रहीत करता है, लेकिन विजुअल स्टूडियो 2008 में संकलन त्रुटि में चला गया। मैंने एक सरलीकृत परीक्षण केस बनाया इसके लिए (नीचे देखें) जो अभी भी वीएस -2008 में संकलित करने में विफल रहता है, लेकिन मैंने कोशिश की ऑनलाइन कॉमौ और ऑनलाइन जीसीसी कंपाइलर्स पर सफलतापूर्वक संकलित करने के लिए दिखाई दिया।विजुअल स्टूडियो 2008

त्रुटि मैं दिखाई दे रही है है:

error C2436: 'func' : member function or nested class in constructor initializer list 
temp.cpp(21) : while compiling class template member function 'test_class<T>::test_class(T (__cdecl &))' 
1>  with 
1>  [ 
1>   T=int (const int &) 
1>  ] 

ही परीक्षण एक गैर टेम्पलेट समारोह काम करता है का उपयोग कर। संक्षेप में, क्या किसी को इस मुद्दे के लिए एक समाधान पता है, या यदि वीएस -2008 इस के लिए किसी प्रकार का अलग वाक्यविन्यास की उम्मीद कर रहा है?

धन्यवाद,

जेरी

template<class T> 
T template_function(const T& arg) 
{ 
    return arg; 
} 

int non_template_function(const int& arg) 
{ 
    return arg; 
} 

template<class T> 
class test_class 
{ 
public: 
    test_class(const T& arg) : func(arg) {} 
private: 
    T func; 
}; 

template<class T> 
void create_class(const T& arg) 
{ 
new test_class<T>(arg); 
} 

int main() 
{ 
    create_class(&template_function<int>); //compile fails unless this is commented out 
    create_class(&non_template_function); 
    return 0; 
} 
+0

+1, अच्छी तरह लिखित, अच्छा न्यूनतम कामकाजी उदाहरण। इसे अधिकृत रूप से उत्तर नहीं दे सकता है लेकिन त्रुटि संदेश में __cdecl लिंकेज के संबंध में अलार्म घंटी बज रहा है। – Flexo

उत्तर

0

यह मुझे test_class में "const t & arg" जैसा दिखता है और create_class आपकी समस्या है। उन्हें सरल "टी तर्क" में बदलना आसान चीजों को लगता है। प्रश्न के लिए

+0

यह बिल्कुल है, धन्यवाद! कोई विचार नहीं कि यह टेम्पलेट फ़ंक्शन के साथ क्यों विफल रहता है, न कि गैर-टेम्पलेट वाला, लेकिन उस परिवर्तन के साथ यह दोनों के लिए काम करता है। – Jerry

+0

एक ही समस्या में भागो, और इस जवाब ने इसे हल किया। धन्यवाद! –

1

यह एक संकलक बग की तरह लगता है, क्योंकि यह वास्तव में सोचता है कि आपको लगता है कि समारोह आह्वान करने के लिए आरंभ करने के बजाय कोशिश कर रहे हैं।

मैं वी.एस. C++ कम्पाइलर की जरूरत नहीं है, लेकिन एक सूचक के रूप में T घोषित समस्या को हल करने हो सकता है:

template<class T> 
class test_class 
{ 
public: 
    test_class(const T& arg) : 
     func(&arg) 
    { 
    } 

private: 
    T *func; 
}; 


template<class T> 
void create_class(const T& arg) 
{ 
    new test_class<T>(arg); 
} 

int main() 
{ 
    create_class(template_function<int>); //compile fails unless this is commented out 
    create_class(non_template_function); 
} 
2

दो स्थानों पर फिक्स;

T* func; //make this pointer type! 

और,

create_class(template_function<int>); //remove '&' 
create_class(non_template_function); //remove '&' 

हो गया!

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