Search code examples
c++templatesheaderdeclarationdefinition

How to correctly declare function with templated class as return type in header?


I have a template class declared in a header file.

// Matrix.h
template <class X> class Matrix {};

In another header file I have a function declaration which has an instantiation of that template class as return type:

// OtherModule.h
Matrix<double> do_stuff();

In the source file of the other module I include the header of the Matrix class:

// OtherModule.cpp
#include "Matrix.h"

Matrix<double> do_stuff() {
  // do stuff
}

How do I make the compiler know what Matrix<double> is in the OtherModule header file without including Matrix.h in the header itself?

I tried forward declaration as shown here:

// OtherModule.h
template class Matrix<double>

Matrix<double> do_stuff();

but it doesn't work.


Solution

  • @n. m. could be an AI: Your first comment accomplishes what I was trying to do. Whether it actually makes sense to do it like that is a seperate question, I guess.

    Anyway with the following code it works:

    // OtherModule.h:
    
    template <class> class Matrix;
    Matrix<double> do_stuff();