0

p.h

#ifndef NODE
#define NODE

#include <iostream>

template <class T>
class Node {
public:
  Node (T e);
  T& getKey();

private:
  T _key;
};

#endif

p.cc

#include "p.h"    

template <class T>
Node<T>::Node(T e){
  this->_key = e;
}

template <class T>
T& Node<T>::getKey(){
  return this->_key;
}

main.cc

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

int main () {
  Node<int> n (100);
  std::cout << n.getKey();
  return 0;
}

g++ --std=c++0x -o main main.cc p.cc

/tmp/ccrIX2he.o: In function `main':
main.cc:(.text+0x19): undefined reference to `Node<int>::Node(int)'
main.cc:(.text+0x25): undefined reference to `Node<int>::getKey()'

I can't instantiate any object from main, but if I include p.cc from main it works or simply if I put together all files also works. How can I make it work this way?

Thanks in advance

Kaner
  • 41
  • 1
  • 3
  • From the duplicate question's answer "_It is not necessary to put the implementation in the header file_" However, it has an answer to your question. Just not to be misleaded – Khalil Khalaf Apr 21 '16 at 15:03
  • 1
    @FirstStep: That statement is 100% correct. Of course, like anything else, it can mislead if you take it out of context and ignore all of the other words in the answer. – Lightness Races in Orbit Apr 21 '16 at 15:05
  • @light I didn't like the title of that question which IS misleading. Templates can be implemented somewhere other than header files and we agree that it is recommended to be somewhere else? – Khalil Khalaf Apr 21 '16 at 15:22
  • @FirstStep: I'll repeat here what I said there: _"@AaronMcDaid: The current wording reflects the common view, however inaccurate. It is therefore a reasonable canonical question. We don't typically put answers in questions! Besides, for all but advanced C++ programmers, this_ might as well be true _as goes general advice. So no I don't think we should edit it."_ But feel free to start a discussion on Meta if you want to seriously propose renaming it. – Lightness Races in Orbit Apr 21 '16 at 15:26
  • _"we agree that it is recommended to be somewhere else"_ Who's recommending that? Nobody sensible recommends that. – Lightness Races in Orbit Apr 21 '16 at 15:27

0 Answers0