在结构上实现c++模板

c++ templates implementing on structures

本文关键字:模板 c++ 实现 结构上      更新时间:2023-10-16

这段c++代码有问题。我在vc++ 6.0中编译了它。它给出了错误"不能推断模板参数的类型"…问题出在display函数。

代码如下:

#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;
template <class type>  
struct one
{
  type data;
  one *next;
};
one<int> *head, *temp, *mid, *del = NULL;
template <class type>
void athead(type value)    
{    
  one *node = new one;    
  node->data = value;    
  node->next = head;    
  head = node;
}
template <class type>
void add_at_tail(type value)   
{
  one *node = new one;   
  node->data = value;    
  node->next = NULL;
  if(head == NULL)
  {
    head = node;   
    temp = head;
  }
  while(temp->next != NULL)   
  {
    temp = temp->next;
  }
  if(temp != node)
  {
    temp->next = node;  
  }
}
template <class type>
void display()
{
  one<type> *temp = new one;
  temp = head;  
  cout << "nn" << endl;   
  while(temp != NULL)   
  {
    cout << " " << temp->data << " " << "->";
    temp = temp->next;
  }
  cout << "nnn";
}
int main()
{
  int a, b, c;
  cout << "Enter the data: " << endl;
  cin >> a;
  add_at_tail(a);
  cout << "Enter the data: " << endl;
  cin >> b;
  add_at_tail(b);
  cout << "Enter the data: " << endl;
  cin >> c;
  add_at_tail(c);
  display();
  return 0;
}

这里至少有几个问题:

首先,您已经定义了模板函数:
template<class type>
void display()
{
    one<type> *temp=new one;
    temp=head;  
    cout<<"nn"<<endl;   
    while(temp!=NULL)   
    {
        cout<<" "<<temp->data<<" "<<"->";
        temp=temp->next;
    }
    cout<<"nnn";
}

这一行是错误的,因为one不是一个完整的类型(one是一个类模板)

one<type> *temp=new one;

你需要这样做:

one<type> *temp=new one<type>;

然后在客户端代码中,您尝试像这样调用函数模板:

display();

但是display是一个没有参数的函数模板,所以编译器无法推断出它的模板形参type的类型。您必须在调用点指定type的类型。

display<int>();

display()的实现也存在逻辑错误。您实例化one的单个副本,而不初始化它。然后你试着像遍历链表一样遍历它,但它不是,它只是你刚创建的某个未初始化的节点。你可能想传入你要迭代的链表。下面的内容:

template<class type>
void display(const one<type>& head)
{
    one<type> const * temp = &head;
    cout<<"nn"<<endl;   
    while(temp!=NULL)   
    {
        cout<<" "<<temp->data<<" "<<"->";
        temp=temp->next;
    }
    cout<<"nnn";
}

既然display接受模板中提到的形参,编译器就能够推断出它的类型。你可能想这样称呼它:

display(head);

您已经调用了display(),但这是一个模板函数,并且您没有给编译器提供推断模板参数的方法。您可以显式地将其指定为display<int>();(但代码除此之外还有其他问题-当您可能应该编写one<type>时,您在几个地方编写了one)。

既然display()没有参数,你认为编译器怎么能弄清楚你希望type具体化为什么类型?您可以给display()一个虚拟的类型参数,或者,更好的是,将所有这些方法移到一个类中,这样整个程序只需计算一次类型参数。

one *node = new one;替换为one<type>* node = new one<type>;,并将main()中的display();更改为display<int>();,修复了所有编译错误。