您可以使用一個額外的靜態成員,其構造函數負責填寫條目的明確模板實例:
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;
}
現在,不同的編譯器支持不同級別的模板遞歸(這個技術是編譯器價格昂貴),所以,小心...「在這裏龍」 ;-)
哦,還有一件事,你並不需要重新定義數組中myClass相關聯的特殊版本,這樣你就可以擺脫實例數組[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;
}
};
前段時間我問了一個類似的問題:http://stackoverflow.com/questions/2850646/fill-container-with-template-parameters。但是用'std :: tr1 :: array'代替這個C風格的數組...... – phlipsy 2010-07-01 12:09:28