Reputation: 4768
I'm building little class called Output ... It's meant to be something that will ease my programming in terms of writing output (like support more types for output to stdout (like QString) and so on ...)
So far it was good, it worked with QString, but now I wanted to make it to accept any type as argument. But while compiling, I get this error:
main.cpp:16: error: undefined reference to `Output& Output::operator<< (int)'
Here's my output class .h and .cpp files:
.h
#ifndef OUTPUT_H
#define OUTPUT_H
#include <QObject>
#include <QTextStream>
class Output : public QObject
{
Q_OBJECT
public:
Output();
template <class _T> Output& operator<<(const _T& Text);
signals:
public slots:
};
extern Output out;
#endif // OUTPUT_H
.cpp
#include "output.h"
Output out;
Output::Output()
{
}
template <class _T> Output& Output::operator <<(const _T& Data)
{
QTextStream s(stdout);
s.setCodec("UTF-8");
s<<Data;
s.flush();
return *this;
}
Upvotes: 1
Views: 937
Reputation: 35901
the linker is right: there is no instantiation of Output::operator << ( const int& )
in your code.
In order for the compiler to generate code for the template, it must be visible at compile time: put your defuinition in the header file and the problem will be solved.
Upvotes: 3
Reputation: 36433
Full template code is needed for instantiation, therefore if you put the code inside a .cpp
file you will only be able to use it inside this file.
Upvotes: 4
Reputation: 42513
You need to implement your template in class declaration, not in class definition. C++ compiler simply not compiling your "Output::operator <<" for "T = int" in .cpp file since it don't "know" that you will use it with "int" in different .cpp file. Moving "Output::operator <<" body from .cpp to .h will fix your problem since .h is included in same compile unit where your code is using template with "int". Unfortunately, i don't remember a correct way to implement templates in .cpp files :(.
Upvotes: 2