Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Undeclared template class error when using friend class with templates

I’m trying to build a custom regular mesh, so I’m having one template class for the cell, and one template class for the mesh.
But it’s giving me an error when trying to make both of them in the same header and both being templates.
Here’s the code:

#include <list>

using namespace std;

template<typename T>
class Cell{
    list<T> points;
public:
    friend class Mesh<T>; // Error here "Explicit specialization of undeclared template class"
    Cell(): points() {}
    void insert(const T &data) { points.push_back(data); }
    T *search(const T &data);
    bool delete(const T &data);
};


template<typename T>
class Mesh { // Error here "Redefinition of 'Mesh' as different kind of symbol"
    float xMin, yMin, xMax, yMax;
    float tamaCellX, tamaCellY;
    vector<vector<Cell<T>>> mr;

    Cell<T> *getCell(float x, float y);
public:
    Mesh(int aXMin, int aYMin, int aXMax, int aYMax, int aNDiv);
    void insert(float x, float y, const T &data);
    T *search(float x, float y, const T &data);
    bool delete(float x, float y, const T &data);
};

What am I doing wrong?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to pre-declare the class template you’re using:

template<typename T>
class Mesh;

This is needed before the Cell definition. However, you also need to change delete members as that’s a reserved keyword. You’ll need to include <vector> as you’re using it. Finally, it’s very much non-recommended to do using namespace std; (because, when you’ll have large projects, you might encounter multiple libs defining their own list, vector, etc.) – just write std:: before standard lib classes.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading