无法从'int'中推断出'Node<T> *'的模板参数
Could not deduce template argument for 'Node<T> *' from 'int'
我目前正在尝试在c ++中实现XOR链表。我尝试使用模板使其通用。此错误在编译时弹出,我无法克服这一点。
我尝试使用模板在谷歌上搜索异或链表,但到目前为止似乎还没有实现它。
XORlinkedlist.h:
#pragma once
#include<iostream>
template <typename T>
struct Node
{
T data;
Node *XORcode;
};
template <typename T>
Node<T> * XOR(struct Node<T> *x, struct Node<T> *y)
{
return (Node<T>*)( (uintptr_t)(x) ^ (uintptr_t)(y) );
}
template <typename T>
class XORlinkedList
{
private:
Node<T> *top, *last;
public:
XORlinkedList()
{
top = last = NULL;
}
void addAtBegin(T data)
{
Node<T> *temp = new Node<T>;
temp->data = data;
temp->XORcode = XOR(top, NULL); //*****ERROR SHOWN IN THIS LINE HERE*****
if(top != NULL)
top->XORcode = XOR(top->XORcode, temp);
top = temp;
}
~XORlinkedList()
{
Node<T> *temp, *storeCode;
temp = top;
storeCode = NULL;
while(top != NULL)
{
temp = top;
top = XOR(top->XORcode, storeCode);
std::cout<<temp->data<<" deletedn";
storeCode = temp->XORcode;
delete temp;
}
}
};
主.cpp:
#include <iostream>
#include "XORlinkedlist.h"
int main()
{
XORlinkedList<int> X;
X.addAtBegin(3);
X.addAtBegin(4);
X.addAtBegin(5);
std::cin.get();
return 0;
}
错误是:
错误 C2784:"节点 *异或(节点 *,节点 *(":无法从"int"推断出"节点 *"的模板参数
只需显式指定一个函数模板参数,例如
temp->XORcode = XOR<T>( top, NULL );
或
temp->XORcode = XOR<T>( top, nullptr );
编译器
无法推断参数类型,因为NULL
不是指针类型。您应该像这样重载您的方法,使用 nullptr
,它是类型 std::nullptr_t
的对象的对象:
// nullptr overload.
template <typename T>
Node<T> * XOR(struct Node<T> *x, std::nullptr_t)
{
return x; // X⊕0 = X
}
template <typename T>
Node<T> * XOR(struct Node<T> *x, struct Node<T> *y)
{
return (Node<T>*)( (uintptr_t)(x) ^ (uintptr_t)(y) );
}
然后,像这样调用该方法:
temp->XORcode = XOR(top, nullptr);
PS:您的构造函数的逻辑似乎有缺陷,可能会导致分段错误。在维基百科或此 C 实现中阅读更多内容(附有解释(。
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 函数调用中参数的顺序重要吗
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 使用不带参数的函数访问结构元素
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 如何使用Luacneneneba API正确读取字符串和表参数
- 在派生函数中指定void*参数
- 视图中的参数推导失败:take_while
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- 使用指向成员的指针将成员函数作为参数传递
- 没有名称的C++模板参数
- 如何将enable-if与模板参数和参数包一起使用