1

I write code for GCC C++. I write class with template called 'graph'.

graph.h:

#include <vector>

template <class T> struct graphNode {
T* elementLink;
std::vector<int> edges;
};

template <class T> class graph {
private:
    std::vector< graphNode<T> > nodes;
    int findElement (T);
public:
    void add(T);
    void addEdge(T, T);
    void deleteEdge(T, T);
    bool isEmpty();
    std::vector<T> getAdjacent(T);
};

graph.cpp(obviously, is not final):

#include "graph.h"

int graph::findElement(T a) {
    for (int i = 0; i < nodes.size(); i++) {
        if (nodes[i] == a) {
            return i;
        }
    }
    return -1;
}

And I got these build errors:

..\graph.cpp:3:24: error: 'template<class T> class graph' used without template parameters
 template <class T> int graph::findElement(T a) {
                        ^
..\graph.cpp: In function 'int findElement(T)':
..\graph.cpp:4:22: error: 'nodes' was not declared in this scope
  for (int i = 0; i < nodes.size(); i++) {
                      ^

What's wrong?

michaeluskov
  • 1,729
  • 7
  • 27
  • 53
  • Unrelated: Sooner or later you're going to be facing another problem, so take the time to read this too: [Why can templates only be implemented in the header file?](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file). – WhozCraig Nov 07 '13 at 20:17

1 Answers1

3

The graph::findElement function is associated with a template and needs a specializaiton or instance with it.

A solution is to place the function in the header file with the template and add the template specification:

template <class T>
int
graph<t>::findElement(T a)
{
//...
}
Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154