I want to overload new operator in a template class. But something wrong happends.
In file test4.h, I defined a class
#include <stddef.h>
#include <iostream>
template <class T>
class lei{
public:
T me;
static void* operator new(size_t size);
};
test4.cpp implement the new operator.
#include "test4.h"
template <class T>
void* lei<T>::operator new(size_t size){
std::cout << size << std::endl;
}
main.cpp
#include "test4.h"
int main(){
lei<size_t> *pl;
pl = new lei<size_t>;
}
I compile the cpp files to .o file. Everything is OK.
But when I link them to the executable file, error occurs:
main.o: In function `main':
main.c:(.text+0x19): undefined reference to `lei<unsigned int>::operator new(unsigned int)'
collect2: ld returned 1 exit status
but everything is OK, if I don’t use template.Why that happens?
So, I hope someone can help me.
You need to put the template implementation in the header file also. The implementation needs to be visible to the compiler when it needs to instantiate the template.
This the C++FAQ 35.12 to learn why this is necessary, and the following entries for ways to fix it.
(Also, your implementation of
operator newshould return something, it should not compile otherwise.)