I am a c++ newbie. Today, I have a problem: in header file, I define a class:
template<class T> class Ptr_to_const {
private:
Array_Data<T>* ap;
unsigned sub;
public:
...
Ptr_to_const<T> & operator=(const Ptr_to_const<T> & p);
};
and in source file, I program as:
template<class T> Ptr_to_const<T>& Ptr_to_const<T>::operator=(
const Ptr_to_const<T> & p) {
...
return *this;
}
when compiled, compiler always say: 'Member declaration not found'. why?
I use eclipse CDT+Cygwin GCC
thank you very much!
Template classes need to be both declared and defined in the header, or another file which is included by users. They can't be declared in a header and defined in a source file like usual.
The reasoning is that the template must be replaced with an actual type and the source for that generated and compiled when used, and the compiler certainly can't precompile templates for every possible type that may come along, so users need to be able to handle that (and so, need access to the code).
This does cause some issues when passing objects, if multiple libraries include the same templates, as they may be compiled against different versions of the header (see the One Definition Rule).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With