【发布时间】:2015-08-14 11:15:31
【问题描述】:
你看,我喜欢结构体,所以我在结构体中放置了一些结构体,并尝试在类模板中使用这些嵌套结构体来声明一些变量。唯一的问题是:它似乎没有按预期工作。这是我的最小示例代码:
#include "stdafx.h"
#include <iostream>
struct T1
{
struct NESTED
{
int var1 = 12345;
};
};
struct T2
{
struct NESTED
{
float var1 = 67890;
};
};
template <typename T > class Proletarian
{
public:
T * t; //works
//T::NESTED * tn; ****** doesn't work! *******
Proletarian<typename T>()
{
T::NESTED * tNested = new T::NESTED; //works
std::cout << tNested->var1;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Proletarian<T1> t1 = Proletarian<T1>();
Proletarian<T2> t2 = Proletarian<T2>();
return 0;
}
我使用 Visual Studio 2013,Intellisense 对我的代码没问题,但它无法编译并出现以下两个错误:
[第 20 行第 1 列] 错误 C2143:语法错误:缺少 ';'在'*'之前
[第 20 行第 1 列] 错误 C4430:缺少类型说明符 - 假定为 int。注意:C++ 没有 支持默认整数
我不太擅长 C++,所以可能不太了解模板是如何工作的以及为什么会发生这种情况。
【问题讨论】:
-
您需要在几个地方指定
typename。 see it live。看到这个问题:"Where and why do I have to put the “template” and “typename” keywords?"。特别是来自 Johannes 的this stellar answer。
标签: c++ class templates struct nested