Tuesday, January 23, 2018

c++ - Define template in header file and definition in a cpp file within derived class

Similar questions have been asked many times on SO already.



But anyways...



First of all, you made some syntax errors.




Instead of



#ifndef  ........
#define .....
template
class abcBaseClass:public abcDerivedClass{
public:
typename getvalue(char*);
};
#endif



it should be something like this.



#ifndef  ........
#define .....
template
class abcBaseClass:public abcDerivedClass{
public:
T getvalue(char*);

};
// Definition follow in this file!
// For reasons or work-arounds, read below.
#endif


Also, both the template declarations and definitions should go into the same file.
One exception is when you instantiate that template to some type in the source file at where the template definition is.



Something like this.




#include "this_template.h"

template
// all sorts of definitions...

// Explicit instantiate this template!!!!
template class abcBaseClass;



Note, a fundamental flaw with this approach is that, you can only use the type you explicitly instantiate in this source file everywhere else in your program. Attempting to instantiate this template with some other type will cause the linker complain about not able to find the matching definition.



If you insist on both the template being generic and having the definition of your template class somewhere else.
You can put the definition into another header file, just call it something like this_template_impl.h and include this_template.h in this_template_impl.h



Then, in your source file, instead of #include "this_template.h", you write #include "this_template_impl.h

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...