Search code examples
c++templatescompiler-errorsincludemember-functions

Declaring a template member function in a tpp file


I have a class A that contains a template member function AFunc. To separate definition from declaration, I declare A and AFunc together in A.h. I then define the member function AFunc in A.tpp and #include "A.tpp" at the bottom of the file A.h.

To me, this all appears like valid C++. However, the Visual Studio compiler throws the error:

A.tpp(8,139): error C2244: 'A::AFunc': unable to match function definition to an existing declaration

The clear solution is to include a declaration for AFunc at the top of the A.tpp file before AFunc is defined. This declaration is in A.h, so we want to include A.h in A.tpp and we want to include A.tpp in A.h. This inclusion is cyclical.

// A.h

class A{
    template <class T>
    void AFunc();
};
#include "A.tpp"
// A.tpp

template <class T>
void A::AFunc(){
    // definition
}

What is the typical solution for dealing with this problem?


Solution

  • Are you giving the compiler the file "A.tpp", or another C++ source file that includes "A.h"? The way you have this structured, I would think the latter would give you the behavior you expect. Apologies, I don't have much VS experience.