c++ - 在结构上使用模板时遇到问题

标签 c++ templates struct

我是编程和 C++ 的初学者。我以前使用过模板,但使用方式非常有限,我不知道自己做错了什么:

template <typename TElement>
struct list{    // if I try list<TElement> => list is not a template
    TElement data;
    struct list *next;
} node_type;    // also tried node_type<TElement>, other incomprehensible errors
node_type *ptr[max], *root[max], *temp[max];

我发现错误有点难以理解:“node_type does not name a type”
我做错了什么?

我打算做什么:
我想要一个类型列表(这样我就可以在几个完全不同的抽象数据类型 - ADT 上使用它),所以我想以这样的方式结束:

Activities list *ptr[max], *root[max], *temp[max]

如果这有意义(其中 Activities 是一个类,但可以是任何其他类)。

最佳答案

试试这个:

template <typename TElement>
struct node{   
    TElement data;
    node* next;
};    

node<int>* ptr[max], *root[max], *temp[max];

另外一个建议:避免使用标准 C++ 库中的类型命名您的自定义类型(例如 listvectorqueue...都在命名空间 std 中)。这很困惑,并可能导致名称冲突(除非您将它放在您自己的命名空间中,您需要在放置 using namespace std; 的任何地方显式使用它)。

关于c++ - 在结构上使用模板时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10802480/

相关文章:

使用动态协议(protocol)类型的 Swift 动态类型初始化

c - 技巧 C 编译器将整个结构分配给零,没有 for 循环

c++ - 在头类构造函数中使用嵌套类

c++ - '[' token c++ 之前的预期不合格 ID

c++ - 初始化使用模板参数作为类型的模板化类的静态成员?

c++ - 为什么 GCC 不允许我将模板参数用于另一个模板的参数?

c++ - 为什么常量的模板特化需要 const 变量

c - 为什么 C 编写的库使用这么多结构?

c++ - 可以在 C++14 constexpr 函数中使用 for 循环实例化模板吗?

android - 如何杀死Cocos2d-x测试应用