2

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 :/

Community
  • 1
  • 1
Ilia Choly
  • 18,070
  • 14
  • 92
  • 160

1 Answers1

2

Function templates must be implemented in the same file in which they are created. See this answer for why.

Community
  • 1
  • 1
David G
  • 94,763
  • 41
  • 167
  • 253