Sír Jeff Meadows
Sír Jeff Meadows

Reputation: 15

C++ Error: class template has already been defined

I am getting this error in Visual Studio 2010 Pro: "Error C2953: 'list_1::Node' : class template has already been defined"

Here is my Node.cpp class list that is getting the error (on line 24, the last line of the code.)

#include "Node.h"

namespace list_1
{
    template <typename T>
    struct Node
    {
        //Constructor
        Node<T>(T D)
        {
            data = d;
            next = NULL;        
        }
    }
;}

And the Node.H file:

#pragma once

namespace list_1
{
    template <typename T>
    struct Node
    {
        T data;
        Node<T> *next;

        // Constructor
        // Postcondition: 
        Node<T> (T d);
    };
}

I already looked here, which doesn't help me since I am already using #pragma once, and in the list header file I have #ifndef LIST_H and #define LIST_H. This question doesn't suit my needs and everything in this answer seems to be related to having the template bit that I already have.

If I try making it struct Node I get the error "error C2753: 'list_1::Node' : partial specialization cannot match argument list for primary template"

So I am at a loss at what to do. Please help.

Upvotes: 1

Views: 7239

Answers (2)

Karthik T
Karthik T

Reputation: 31952

I agree with your compiler.. You are defining the struct twice.

To fix -

Remove from your header.

And your .cpp should look like this.

#include "Node.h"

namespace list_1
{
    //Constructor
    template<typename T>
    Node<T>::Node(T D){
        ...
    }
}

Essentially, the struct block only appears in the header.

Additionally I wonder if you are aware of the problems involving defining the template classes members in a .cpp file

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490098

For a normal (non-template) class, you'd do something like this:

//whatever.h
namespace Y 
    class X {
    public:
        X();
    };
}

Then in the cpp file, you'd have something like:

namespace Y { 
    X::X() { /* ... */ }
}

For a template, however, you normally need to put the implementation where the compiler will have seen it anywhere it's going to be used, which normally means putting into the header as well. That being the case, quite a few people just write the definitions as inline definitions inside the class definition:

namespace Y { 
    template <class T>
    class X {
    public:
        X(T d) { /* ... */ }
    };
}

You can define the function(s) outside the class definition if you want, but since they're going to be the header anyway, that doesn't really accomplish a lot (at least in the typical case).

Upvotes: 2

Related Questions