有多個靜態變數的類,例如
template<class T>
struct A
{
// some code...
static int i;
static short s;
static float f;
static double d;
// other static variables
};
主要方式是使用完整的模板名稱
template<typename T>
int A<T>::i = 0;
template<typename T>
short A<T>::s = 0;
template<typename T>
float A<T>::f = 0.;
template<typename T>
double A<T>::d = 0.;
// other inits of static variables
這個解決方案包含很多相同的代碼(template<typename T>和A<T>)如果模板有幾種型別,這會導致增加這個代碼,例如
struct B<T1, T2, T3, T4>
{
// some code
static int i;
//other static variables
};
...
template<typename T1, typename T2, typename T3, typename T4>
int B<T1, T2, T3, T4>::i = 0;
//other static variable
1-2個靜態變數看起來不錯,但如果你需要更多它看起來很糟糕我考慮使用宏,像這樣
#define AStaticInit(TYPE) template<typename T> TYPE A<T>
AStaticInit(int)::i = 0;
AStaticInit(short)::s = 0;
AStaticInit(float)::f = 0.;
AStaticInit(double)::d = 0.;
// other inits of static variables
#undef TArray
但也許有更好的選擇來用最少的代碼初始化模板類中的幾個靜態變數?
uj5u.com熱心網友回復:
讓他們inline能夠給他們初始化:
template<class T>
struct A
{
// some code...
inline static int i = 0;
inline static short s = 0;
inline static float f = 0.f;
inline static double d = 0.;
// other static variables
};
uj5u.com熱心網友回復:
創建一個不需要模板的基類并將所有靜態變數放入其中。
struct Base
{
// some code...
static int i;
static short s;
static float f;
static double d;
// other static variables
};
template<class T>
struct A : public Base
{
// some code...
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/508188.html
