我有一些奇怪的問題,試圖初始化模板類的靜態const成員變量。我所有的其他靜態變量初始化都很好,但由於某種原因,它不喜歡這個。我將一些示例代碼放在一起進行測試,但它沒有問題,所以我真的不知道發生了什麼。C++靜態const模板成員初始化
除此之外,我還遇到了定義函數的問題,這些函數使用模板類中聲明的類型定義,並且具有相同的問題,說明找不到類型。這個問題我已經能夠在下面的代碼中重現。我知道解決這個問題的一種方法是在類中定義函數,但函數非常大,我試圖保持它與在類之外定義的所有巨大函數一致以使類定義更容易讀書。如果這是我唯一的選擇,雖然那麼我想我會破例......
class tTestType
{
public:
tTestType(int32_t val) : fValue(val) { }
private:
int32_t fValue;
};
template<class T>
class tTestTemplate
{
public:
tTestTemplate() { }
private:
typedef std::vector<int32_t> tSomeVec;
tSomeVec mTestFunction() const;
static const tTestType kTestStatic;
};
// Should cause the following errors but I can't reproduce them for some reason:
// error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
// error C2988: unrecognizable template declaration/definition
// error C2059: syntax error : 'constant'
template<class T>
const tTestType tTestTemplate<T>::kTestStatic(10);
// Causes the following errors:
// error C2143: syntax error : missing ';' before 'tTestTemplate<T>::mTestFunction'
// error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
// fatal error C1903: unable to recover from previous error(s); stopping compilation
template<class T>
tTestTemplate<T>::tSomeVec tTestTemplate<T>::mTestFunction() const
{
tSomeVec result;
result.push_back(0);
return result;
}
這是一個「發現差異」的難題嗎?你做了什麼改變,爲什麼? – bk1e 2012-01-04 04:18:15
我不認爲它是一個差異拼圖。我改變了mTestFunction()的定義方式。 – Raghuram 2012-01-04 04:42:40
所以你剛剛在課堂外移動了typedef?你可以這麼說。我想這也是另一種解決方案。有些事情要考慮,謝謝。我還有其他問題,就像我說的,示例代碼沒有問題。我真的只是想看看是否有人可能知道什麼可能會導致我在關於靜態成員聲明的註釋中指定的錯誤。 – Shenjoku 2012-01-04 19:06:51