【发布时间】:2012-02-02 01:13:25
【问题描述】:
我在尝试初始化模板类的静态 const 成员变量时遇到了一些奇怪的问题。我所有的其他静态变量都初始化得很好,但由于某种原因它不喜欢这个。我整理了一些示例代码进行测试,它没有问题所以我真的不知道发生了什么。
除此之外,我在定义使用在模板类中声明的 typedef 的函数时也遇到了问题,同样的问题是找不到类型。这个问题我已经能够在下面的代码中重现。我知道修复它的一种方法是在类内部定义函数,但函数非常大,我试图使其与在类外部定义所有巨大函数保持一致,以使类定义更容易阅读。如果这是我唯一的选择,那么我想我将不得不破例......
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;
}
【问题讨论】:
标签: c++ templates static initialization constants