कारण आप टेम्पलेट श्रेणी को एक .cpp फ़ाइल में नहीं डाल सकते हैं क्योंकि एक .cpp फ़ाइल को "संकलित" करने के लिए आपको यह जानने की आवश्यकता है कि टी के स्थान पर किस प्रकार का उपयोग किया जा रहा है। एक टेम्पलेटेड क्लास (जैसे आपकी कक्षा जे) में संकलन करने के लिए पर्याप्त जानकारी नहीं है। इस प्रकार यह सभी शीर्षकों में होना चाहिए।
यदि आप सफाई के लिए किसी अन्य फ़ाइल में कार्यान्वयन को तोड़ना चाहते हैं, तो सर्वोत्तम अभ्यास एक .hxx फ़ाइल का उपयोग करना है। इस तरह: अपने हेडर फाइल के अंदर, Jh, डाल:
#ifndef _J_H__
#define _J_H__
template <class T> class J{ // member definitions };
#include "j.hxx"
#endif // _J_H__
और फिर, j.hxx में आपको मिलने वाले
template <class T> J<T>::J() { // constructor implementation }
template <class T> J<T>::~J() { // destructor implementation }
template <class T> void J<T>::memberFunc() { // memberFunc implementation }
// etc.
अंत में अपने .cpp फ़ाइल में
टेम्प्लेटेड वर्ग का उपयोग करता है, चलो चलो यह K.cpp फोन आप होगा:
#include "J.h" // note that this always automatically includes J.hxx
void f(void)
{
J<double> jinstance; // now the compiler knows what the exact type is.
}
स्रोत
2011-04-10 17:38:55
एक उत्तर सी ++ पूछे जाने वाले प्रश्न में मौजूद है: http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12 – birryree