无法从'int'中推断出'Node<T> *'的模板参数

Could not deduce template argument for 'Node<T> *' from 'int'

本文关键字:gt 参数 推断出 int Node lt      更新时间:2023-10-16

我目前正在尝试在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 实现中阅读更多内容(附有解释(。