2012-11-15 4 views
1

가능한 중복 unique_ptr : 지금 2 일 동안이 문제를 알아 내기 위해 노력했습니다
Why can templates only be implemented in the header file?이상한 링커 오류 :

.

main.cpp:17: undefined reference to `std::unique_ptr<Foo, std::default_delete<Foo> > Bar::make_unique_pointer<Foo>()' 

아래의 코드가 나는 데 문제를 보여줍니다

여기에 내가 갖는 링커 오류입니다.

는 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; 
} 

I 함수를 정의하지만 만약 인라인, 그것은

class Bar { 
public: 
    template <class T> 
    std::unique_ptr<T> make_unique_pointer() { 
     return std::unique_ptr<T>(new T()); 
    } 
}; 

를 작동 또는 내가 main.cpp의 정의를 넣어 경우 또는 Bar.h에서 잘 컴파일됩니다./

+0

입니다. 나는 정확한 용어를 찾고 있지 않았습니다. 닫히기로 결심했다. –

답변

2

기능 템플릿은 생성되는 동일한 파일에 구현되어야한다 : 그들은 별도의 파일에있을 때

나는 단지 링커 오류가 발생합니다. See this answer for why.