Possible Duplicate:
Why can templates only be implemented in the header file?
I've been trying to figure this out for 2 days now.
Here's the linker error I'm getting:
main.cpp:17: undefined reference to `std::unique_ptr<Foo, std::default_delete<Foo> > Bar::make_unique_pointer<Foo>()'
The code below demonstrates the issue I'm having.
Bar.h
class Bar {
public:
template <class T>
std::unique_ptr<T> make_unique_pointer();
};
Bar.cpp
#include "Bar.h"
template <class T>
std::unique_ptr<T> Bar::make_unique_pointer() {
return std::unique_ptr<T>(new T());
}
main.cpp
#include "Bar.h"
struct Foo {};
int main() {
Bar bar;
auto p = bar.make_unique_pointer<Foo>();
return 0;
}
However if I define the function inline, it works
class Bar {
public:
template <class T>
std::unique_ptr<T> make_unique_pointer() {
return std::unique_ptr<T>(new T());
}
};
Or if I put the definition in main.cpp
or even in Bar.h
it will compile fine.
I only get the linker error when they're in separate files :/