【问题标题】:using a template with a struct incomplete type error使用带有结构不完整类型错误的模板
【发布时间】:2020-07-01 16:02:13
【问题描述】:
#include <iostream>
#include <string>
#include <map>
using namespace std;

template<typename T>
struct Node
{
    map<string, T> data;
    struct Node* left, * right, * bottom;
    Node(map<string, T> data)
    {
        this->data = data;
        left = right = bottom = NULL;
    }

};


int main()
{
    cout << endl;
   
    map <string, string> test;
    test["walid"] = "walid";
    struct Node* root = new Node(test); #error here
    cout << root->data["walid"];


    cout << endl;


    return 0;
}

谁能告诉我为什么我收到不完整的类型错误?我正在尝试根据数据使用不同的地图值类型创建节点。

【问题讨论】:

  • Node 是模板类型,您没有指定模板参数。
  • 你应该edit你的帖子引用完整的错误,请。
  • 研究推导指南,看看如何避免指定类型参数并让它从构造函数调用中推导出来。

标签: c++ dictionary templates struct


【解决方案1】:

谁能告诉我为什么我收到不完整的类型错误?

因为您正在尝试创建指向您尚未定义的类型的指针/尝试创建您尚未定义的类型的动态对象。

您尚未定义名为Node 的类型。您已经定义了一个名为Node 的类模板。您不能拥有Node*,原因与您不能拥有std::vector* 的原因相同。这个编译器错误解释了发生了什么:

error: template argument required for 'struct Node'

您可以实例化模板以获得一个类,它是一个类型。尖括号语法用于实例化模板,并传递模板参数。示例:

Node<std::string>* root = ...

请注意,如果让编译器从初始化器中推断出指针的类型,那么编译器可以隐式推断类模板参数(该语言特性是在 C++17 中引入的):

auto* root = new Node(test);

附:如果编译,您的示例会泄漏内存。避免裸拥有指针。更喜欢 RAII 容器和智能指针。不需要时也要避免动态分配。

【讨论】:

    【解决方案2】:

    Node 不是类型,而是模板。 Node&lt;string&gt; 是你想要的类型。

    此外,变量声明中的struct 在 C++ 中是多余的,因此将该行更改为:

    Node<string>* root = new Node<string>(test);
    

    以后别忘了delete root;——或者你可以把root设为一个值:

    Node<string> root{test};
    

    最后,你可以在这里用std::move优化几处,比如:

    Node(map<string, T> data)
    {
        this->data = data;
        left = right = bottom = NULL;
    }
    

    使用初始化列表和std::move,您可以节省一份可能很昂贵的data

    Node(map<string, T> d) :
        data{std::move(d)},
        left{nullptr}, right{nullptr}, bottom{nullptr} {}
    

    同样,由于您再也不会使用test,您可以将其移至构造函数参数中:

    Node<string> root{std::move(test)};
    

    【讨论】:

      猜你喜欢
      • 2015-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-21
      • 1970-01-01
      • 2014-11-22
      相关资源
      最近更新 更多