Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ error: Member declaration not found

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!

like image 723
wenfeng Avatar asked Jan 13 '12 08:01

wenfeng


1 Answers

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).

like image 189
ssube Avatar answered Sep 18 '22 11:09

ssube