Mohamed Elhaware
Mohamed Elhaware

Reputation: 1

how to make a linked list with template

i have problems with distributing template. i tried with different syntax, but not a successful way with the error text:

error C2512: 'node': no appropriate default constructor available

for the code

#include<iostream>
using namespace std;
template<class t>
class node {
    public:
        t data;
        node<t> * next;
};
template<class t>
class linkedlist {
    node<t>* head;
public:
    linkedlist() { head = NULL; }
    bool isempty() {
        return head == NULL;
    }
    void insertf(t value) {
        node<t>* newnode = new node;

        newnode->data = value;
        newnode->next = NULL;
        if (isempty()) {
            head = newnode;
        }
        else {
            newnode->next = head;
            head = newnode;
        }
    }
    void display() {
        node<t>* tem;
        tem = head;
        while (tem != NULL) {
            cout << tem->data<<" ";
            tem = tem->next;
        }
    }
};

Upvotes: -1

Views: 47

Answers (1)

HolyBlackCat
HolyBlackCat

Reputation: 96791

Always start by reading the first error message.

error C2512: 'node': no appropriate default constructor available

This isn't the first one. The complete error is:

<source>(18): error C2641: cannot deduce template arguments for 'node'
<source>(18): note: the template instantiation context (the oldest one first) is
<source>(10): note: while compiling class template 'linkedlist'
<source>(18): error C2783: 'node<t> node(void)': could not deduce template argument for 't'
<source>(4): note: see declaration of 'node'
<source>(18): error C2780: 'node<t> node(node<t>)': expects 1 arguments - 0 provided
<source>(4): note: see declaration of 'node'
<source>(18): error C2512: 'node': no appropriate default constructor available

(If you don't see this, make sure you look at the Output tab as opposed to Errors.)

The first error points to this line: node<t>* newnode = new node;.

In case it's not clear, cannot deduce template arguments for 'node', means you're missing <t> after node.


Also, for the future questions, make sure to provide the complete error from the Output tab.

Also (as you can check here), you don't get the error until you either try to call insertf() or add /std:c++latest to compiler flags. This information must be in the question (either you omitted some code, or didn't say what compiler flags you used).

Upvotes: 4

Related Questions