在结构上实现c++模板
c++ templates implementing on structures
这段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>();
,修复了所有编译错误。
相关文章:
- .cpp和.h文件中的模板专用化声明
- C++模板来检查友元函数的存在
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 如何在c++中为模板函数实例创建快捷方式
- 使用C++中的模板和运算符重载执行矩阵运算
- 有人能分解一下这个c++模板的语法吗
- 如何在c++17中制作一个模板包装器/装饰器
- 模板化建造师专业化
- 调用专用模板时出错"no matching function for call to [...]"
- 模板元程序查找相似的连续类型名称
- 如何在C++20中创建模板别名的推导指南
- 没有名称的C++模板参数
- 具有重复类型的C++可变模板
- 如何将enable-if与模板参数和参数包一起使用
- 没有用于初始化C++中的变量模板的匹配构造函数