0

Here is the code for the question:

PlainInterface.h

/** PlainInterface.h */
#ifndef _PLAIN_INTERFACE
#define _PLAIN_INTERFACE

#include <vector>

template <class ItemType>
class PlainInterface{
public:
    virtual int getSize () const = 0;
}; 
#endif

Plain.h

/** Plain.h */
#ifndef _PLAIN
#define _PLAIN
#include "PlainInterface.h";

template <class ItemType>
class Plain: public PlainInterface < ItemType > {
private:
    std::vector<ItemType> a;

public:
    Plain();
    ~Plain();

    int getSize() const;
};
#include "Plain.cpp"
#endif

Plain.cpp

/* Plain.cpp */
#include <iostream>
#include "Plain.h"

//Constructors
template <class ItemType>
Plain<ItemType>::Plain() {
    std::cout << "Created\n";
}

template <class ItemType>
Plain<ItemType>::~Plain() {
    std::cout << "Destroyed\n";
}

template <class ItemType>
int Plain<ItemType>::getSize() const { return 0; }

So according to this question it said that you can either have all of the implementation in the header file, or put #include "Plain.cpp" at the end of the "Plain.h" file, or put the explicit instantiations at the end of the "Plain.cpp" file. I would like to keep the files seperate and not limit what is allowed into the templates. I tried the second option and it didn't work. The errors that I am getting are that the constructor/deconstructor/getSize definitions in Plain.cpp are already defined. What am I doing wrong here?

Community
  • 1
  • 1
kingcobra1986
  • 971
  • 2
  • 14
  • 38

1 Answers1

0

You should remove #include "Plain.h" in your .cpp file, as you are creating a circular include otherwise.

Example:

//a.h
...
#include "b.cpp"

//b.cpp
#include "a.h"

a will include b, b will include a, and so on. This is probably why the second option you mentioned didn't work.

Here another answer that applies to your problem (I think): https://stackoverflow.com/a/3127374/2065501

Community
  • 1
  • 1
user2065501
  • 99
  • 2
  • 9
  • So what is the proper way to keep the three files separated and it still would work even with the templates? – kingcobra1986 Jul 13 '16 at 10:37
  • @kingcobra1986 I actually copy-pasted your code into one of my projects, and removed the `#include "Plain.cpp"` part in the header, and everything compiled perfectly? – user2065501 Jul 13 '16 at 11:04
  • So do you think it's just because I'm using visual studio? – kingcobra1986 Jul 13 '16 at 20:00
  • @kingcobra1986 I'm using visual studio too. So it's kind of weird, because as I said, I just copy-pasted your code and deleted the `#include Plain.cpp` part, and it compiled perfectly. Then again, maybe I'm just being stupid right now and I'm missing something real big. – user2065501 Jul 15 '16 at 14:10