0

I am trying to use template but it does not work, the error is : " previously declared here"

this is my Matrix.h file:

#ifndef MATRIX_H
#define MATRIX_H

template <class T>
class Matrix
{
public:
     Matrix(int); // default cunstractor

private:
    int rows, columns;
};

#include "Matrix.cpp"
#endif

and this is my Matrix.cpp file

#include "Matrix.h"
#include<iostream>
using namespace std;

template <class T>
Matrix<T>::Matrix(int a) // Default constructor
{
   columns = a;
   rows = 0;
}

and this is the main file:

#include<iostream>
#include "Matrix.h"
using namespace std;

int main()
{

Matrix<int> m1(5);
return 0;
}

I know the code seems very stupid and simple but I wrote much more, I reduce it to very simple code like this and again it doesn't work. Even I removed

#include "Matrix.cpp"

inside the Matrix.h file but still have problem.

MoHo
  • 2,402
  • 1
  • 21
  • 22
  • 1
    `#include "Matrix.cpp"` inside Matrix.h. You should be notified that .cpps are never, EVER, E V E R! included – Creris Nov 20 '14 at 18:26
  • This is not about that topic... It's all about an error which doesn't mean any thing to me... – MoHo Nov 20 '14 at 18:27
  • Template definitions *must* be in the header. See [this question](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – Barry Nov 20 '14 at 18:29
  • I include cpp file in header file as you can see at he very end of Matrix.h file – MoHo Nov 20 '14 at 18:34
  • 1
    " previously declared here" is not an error message, it's part of a note giving you more information about a previous error message. – sepp2k Nov 20 '14 at 18:43

1 Answers1

1

Move the content (template definition) of your matrix.cpp file to matrix.h.

  • I know I can do it but this is not the solution – MoHo Nov 20 '14 at 18:39
  • http://www.parashift.com/c++-faq-lite/templates-defn-vs-decl.html http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file – learningToCode Nov 20 '14 at 18:41
  • 1
    @user1796381: This is the solution. If you really want to do your weird shenanigans of including the source file from the header, then don't also include the header from the source file. But seriously: just define the template in the header. – Mike Seymour Nov 20 '14 at 19:02