Frage

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???

War es hilfreich?

Lösung

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);
    }
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top