以下看似正确的代码无法在 Visual Studio 2015 RC 中编译,并出现如下错误:
test.cpp(6): error C2098: unexpected token after data member 'T'
test.cpp(11): note: see reference to class template instantiation 'Foo<int>' being compiled
test.cpp(6): error C2059: syntax error: '>'
代码:
template <typename, typename> struct X {};
template <typename T>
struct Foo
{
X<int, T> * p = new X<int, T>;
};
int main()
{
Foo<int> f;
}
为什么会这样,我该如何克服这个问题?
您的编译器似乎没有正确实现 C++,特别是大括号或等于初始化程序。
一个简单的解决方法是用构造函数初始化器替换大括号或等于初始化器:
template <typename T>
struct Foo
{
Foo() : p(new X<int, T>) {}
// ^^^^^^^^^^^^^^^^
X<int, T> * p; // no initializer
};
历史记录:在我将其替换为重现错误的最小示例之前,您原始帖子中的修复:
class ArdalanCollection : public ICollection<T>
{
public:
ArdalanCollection()
: storage(new Container_<int, T*>()), index(0) {}
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
virtual void add(T* obj) {
storage->add(index++, obj);
};
private:
Container_<int, T*> *storage; // no initializer here
int index;
};