2012-11-15 126 views
1

可能重复:
Why can templates only be implemented in the header file?奇怪的链接错误::的unique_ptr

我一直在努力,现在算出这个2天。

这里的链接错误我得到:

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

但是如果我定义函数内联,它的工作原理

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

绝对。我只是没有搜索正确的条款。投票结束。 –

回答