1

I am puzzled...

This is the *.h-file:

#include <string>
#include <vector>

template<typename T>
class pvector
{
private:
    std::string filename;
    std::vector<T> v;
    void readvector();

public:
    pvector(std::string fname) : filename(fname) { readvector(); }
    void push_back(const T &el) { v.push_back(el); }
    void pop_back() { v.pop_back(); }
};

And this is the *.cpp:

#include <fstream>
#include <string>
#include "pvector.h"

using namespace std;

template<typename T>
void pvector<T>::readvector()
{
    ifstream ifs(filename);
    for(;;)
    {
        T x; ifs >> x; if(!ifs.good()) break;
        v.push_back(x);
    }
}    

If I want to generate the following object:

pvector<string> myVec("testfile.txt");

... i get:

pvector.h:24: undefined reference to `pvector::readvector()'

Why???

Michael
  • 706
  • 9
  • 29
  • 1
    http://stackoverflow.com/questions/18543980/symbol-not-found-when-using-template-defined-in-a-library/18544093#18544093 That answer is exactly what you want (I am also proud of it) it both explains the error and there's a fix in there to. – Alec Teal Oct 23 '13 at 16:57
  • Thanks a lot for the hints... I am studying templates at the moment and was not aware of this. – Michael Oct 23 '13 at 20:05

1 Answers1

4

you need to define below function in header file itself instead of .cpp file.

template<typename T>
void pvector<T>::readvector()
{
    ifstream ifs(filename);
    for(;;)
    {
        T x; ifs >> x; if(!ifs.good()) break;
        v.push_back(x);
    }
}
Vishnu Kanwar
  • 761
  • 5
  • 22