2011年10月2日 星期日

c++ class template cannot find its constructor

c++ class with template cannot find its constructor
http://stackoverflow.com/questions/644397/c-class-with-template-cannot-find-its-constructor

[35.12] Why can't I separate the definition of my templates class from its declaration and put it inside a .cpp file?
http://www.parashift.com/c%2B%2B-faq-lite/templates.html#faq-35.12


A template is not a class or a function. A template is a "pattern" that the compiler uses to generate a family of classes or functions.

In order for the compiler to generate the code, it must see both the template definition (not just declaration) and the specific types/whatever used to "fill in" the template. For example, if you're trying to use a Foo<int>, the compiler must see both the Foo template and the fact that you're trying to make a specific Foo<int>.

Your compiler probably doesn't remember the details of one .cpp file while it is compiling another .cpp file. It could, but most do not and if you are reading this FAQ, it almost definitely does not. BTW this is called the "separate compilation model."

class template不是class,只是個pattern。compiler看到class template並不會製造出class,除非有使用到,才會在編譯過程中嘗試造出。

製造時,她必須要有class template的宣告與定義(實作),才能造出class method。
但compiler不會去記他之前看過的檔案,所以在有使用到template class的檔案裡,不只要include宣告,還要include定義(實做)。

/*A.hpp*/
template<class T>
class A
{...}

/*A.cpp*/
#include"A.hpp"
...

/*Main.cpp*/
#include"A.cpp"

另一種解法:(如果是用A<bool>)

/*A.hpp*/
template<class T>
class A
{...}

/*A.cpp*/
#include"A.hpp"
...
template class A<bool>; //令compiler現在就把A<bool>造出來

/*Main.cpp*/
#include"A.hpp"
//you can use A<bool>

如果你不能修改A.cpp的話,可以這樣:
/*A-impl.cpp*/
#include"A.cpp"
template class A<bool>;

沒有留言:

張貼留言