0

I have a problem with the derivation of template classes. The following code-snippet will show my problem:

class object {
}

template <class T>
class container {
public:
    cotainer(void) {
        // do some work
    }
}

template <class in, class out>
class stage {
private:
    container<in> *input;
    container<out> *output;
public:
    stage(bool input, container<out> *output) {
        // do some other work
    }
}

After that, I want to derive from stage. I get no error, if the derived class is also a template class like:

template <class T>
class derived : public stage<T, T> {
public:
    derived(container<T> *output) : stage<T, T>(false, output) {}
}

But, if the derived class is a specialization of stage, I get an error.

class derived : public stage<object, object> {
public:
    derived(container<object> *output) : stage<object, object>(false, output) {}
}

The error is, that the compiler does not find the constructor of stage.

undefined reference to `stage<object, object>::stage(bool, container<object>*)'

How can I solve the problem?

  • 1
    This is certainly not your code (missing semicolons, typos etc.), could you please provide an example that can be compiled to the point where the (linker) error appears? – filmor Mar 18 '13 at 12:03
  • 1
    Compiles for me (after I fixed the typos) when all in one file. I suspect the problem is related to how you distribute your code among headers and source files. – us2012 Mar 18 '13 at 12:07
  • 1
    Agree with @us2012, you most likely have the definitions of your class template's member functions in a `.cpp` files (including the constructor, which the linker seems to complain about). If that's the case, see [this question](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) and move those member function definitions into the header where the corresponding class template is defined. – Andy Prowl Mar 18 '13 at 12:14
  • Okay, thanks. This works for me, but looks somehow dirty and stupid. Is it a general compiler problem or only GCC's one? – user2182164 Mar 18 '13 at 12:22
  • @user Well, see the second-highest voted answer to the question in Andy Prowl's link - you can explicitly instantiate the templates in the file where you define them. But I'm not convinced that this is 'cleaner' in general. – us2012 Mar 18 '13 at 12:33

0 Answers0