Error: class template has already been defined

2019-02-19 13:20发布

问题:

I have this small template class:

namespace emple {
    template <class LinkedClass> 
    class LinkedInList 
    {
    public:
        LinkedInList()
        { 
            active = false; 
        }
        ~LinkedInList(){}
        LinkedClass* getNext() const
        {
            return next;
        }
        void setNext(LinkedClass* const next_)
        {
            next = next_;
        }
        void setActive(bool state)
        {
            active = state; 
        }
        bool isActive()
        { 
            return active; 
        }
    private:
        LinkedClass* next;
        bool active;
    };
};

When compiling I get this error:

class template has already been defined.

What am I doing wrong?

回答1:

This is caused by multiply including the same header file (which contains this template class). This is typically solved in C++ by either using guards:

#ifndef EMPLE_H
#define EMPLE_H

// your template class

#endif

or #pragma onces (which are supported by every compiler I know) and are less cluttering:

#pragma once

// your template class