0

i'm getting "undefined reference to ... " errors. Though, i can't find any error in the code.

main.cpp:11: undefined reference to `Grid::Grid(int, int)'

This happens for all the methods of the 2 classes, so i'm going to write here just one class, feel free to ask for the other one too (The other one is a pretty long code).

main.cpp:

#include <iostream>
#include "Grid.h"

using namespace std;

int main() {
    Grid<int> a(5, 5);

    return 0;
}

Grid.h:

#ifndef GRID_H
#define GRID_H

#include <vector>

using namespace std;

template <class T>
class Grid{
private:
    int W, H;
    vector<vector<T>> grid;
    Grid();
public:
    Grid(int w, int h);

    bool SetContent(int x, int y, T content);
    T GetContent(int x, int y);
};

#endif /* GRID_H */

Grid.cpp:

#include "Grid.h"
#include <vector>

using namespace std;

template <class T> 
Grid<T>::Grid(){}

template <class T>
Grid<T>::Grid(int w, int h){
    W = w;
    H = h;
    grid.resize(h);
    for(int y = 0; y < h; y++)
        grid[y].resize(w);
}

template <class T>
bool Grid<T>::SetContent(int x, int y, T content){
    if(x > 0 && x < W && y > 0 && y < H){
        grid[x][y] = content;
        return true;
    }
    return false;
}

template <class T>
T Grid<T>::GetContent(int x, int y){
    if(x > 0 && x < W && y > 0 && y < H){
        return grid[x][y];
    }
    return grid[x][y];
}

This is the compiler command, if necessary (I guess it's a compiling error):

g++ -o dist/Debug/MinGW-Windows/pacman build/Debug/MinGW-Windows/Grid.o build/Debug/MinGW-Windows/Vector2.o build/Debug/MinGW-Windows/WinAPI_Console.o build/Debug/MinGW-Windows/main.o -static-libgcc -static-libstdc++

If you need more informations, just ask, i'll wait for replies here.

  • templates should be defined in the header http://stackoverflow.com/questions/115703/storing-c-template-function-definitions-in-a-cpp-file – PapaDiHatti May 22 '17 at 07:11
  • Note that both your `SetContent` and `GetContent` has a flaw in that it doesn't allow index zero. The `GetContent` function also has another flaw when `x` or `y` are not in range leading to out-of-range indexing. – Some programmer dude May 22 '17 at 07:16
  • Noticed that now, thank you. Still, i don't understand why i can't use templates in the implementation file... The only way i have understood is instantiating the class with `template class Grid;` in the implementation file, but that's not what i want at all. I would've to edit the class everytime i need a different type. – Simone Bondi May 22 '17 at 07:36

0 Answers0