आप एक अतिरिक्त स्थिर सदस्य जिसका निर्माता प्रविष्टियों को भरना का ख्याल रखता है की स्पष्ट टेम्पलेट इन्स्टेन्शियशन उपयोग कर सकते हैं:,
template<int length>
class myClass{
public:
static int array[length];
typedef enum{LENGTH=length} size_;
struct filler
{
filler(void)
{
for(int i=0;i<LENGTH;++i)
array[i]=i+1;
}
};
static filler fill_;
};
// of course, the line[s] below now do work as intended.
template<int length>
int myClass<length>::array[length];
//static member definition
template<int length>
typename myClass<length>::filler myClass<length>::fill_;
//explicit template instantiation
template myClass<5>::filler myClass<5>::fill_;
int main(void)
{
for(int i=0;i<myClass<5>::LENGTH;++i)
cout<<myClass<5>::array[i]<<endl;
return 0;
}
या के बाद से एक समान (शायद बेहतर) समाधान पहले से ही बेनोइट द्वारा ऊपर दिखाया गया है, यहां एक टेम्पलेट पुनरावर्ती संस्करण है, सिर्फ मनोरंजन के लिए:
//recursive version:
template<int length>
class myClass{
public:
static int array[length];
typedef enum{LENGTH=length} size_;
static void do_fill(int* the_array)
{
the_array[LENGTH-1]=LENGTH;
myClass<length-1>::do_fill(the_array);
}
struct filler
{
filler(void)
{
/*for(int i=0;i<LENGTH;++i)
array[i]=i+1;*/
do_fill(array);
}
};
static filler fill_;
};
//explicit specialization to end the recursion
template<>
class myClass<1>{
public:
static int array[1];
typedef enum{LENGTH=1} size_;
static void do_fill(int* the_array)
{
the_array[LENGTH-1]=LENGTH;
}
};
//definition of the explicitly specialized version of the array
//to make the linker happy:
int myClass<1>::array[1];
// of course, the line below does not work as intended.
template<int length>
int myClass<length>::array[length];
//static member definition
template<int length>
typename myClass<length>::filler myClass<length>::fill_;
//explicit template instantiation
template myClass<5>::filler myClass<5>::fill_;
int main(void)
{
for(int i=0;i<myClass<5>::LENGTH;++i)
cout<<myClass<5>::array[i]<<endl;
return 0;
}
अब, विभिन्न compilers टेम्पलेट प्रत्यावर्तन के विभिन्न स्तरों का समर्थन (और इस तकनीक संकलक महंगा है) हां, तो सावधान ...;-)
ओह "यहाँ ड्रेगन रहो", एक और बात, आप myClass के विशेष संस्करण में सरणी को फिर से परिभाषित करने के लिए है, तो आप सरणी instantiating से छुटकारा पा सकते की जरूरत नहीं है [1]:
//explicit specialization to end the recursion
template<>
class myClass<1>{
public:
typedef enum{LENGTH=1} size_;
static void do_fill(int* the_array)
{
the_array[LENGTH-1]=LENGTH;
}
};
स्रोत
2010-07-01 16:38:43
मैं एक ऐसी ही प्रश्न पूछा कुछ समय पहले: http://stackoverflow.com/questions/2850646/fill-container-with-template-parameters। लेकिन इस सी-शैली सरणी के बजाय 'std :: tr1 :: array' के साथ ... – phlipsy