Hello World Hello World - 4 months ago 17
C++ Question

C++:: #include:ing template class header file in multiple source files?

I am using this class with--all except for one--template member functions, which will be used in a project with multiple source files which get linked on compilation. The template type is unknown and can take just about any type to it. In this case I have two source files which use the class, therefore the header file with the class declaration and definition is #include:ed in both source files. I then get the error "multiple definition" at the non-template member function declaration of the class. I presume that is because it is being defined twice during the linking process since both source files have a definition of the non-template member function. Imagine the non-sense scenario below:

Note: Assume all files are include guarded and iostream is #include:ed wherever required.

foo.hpp

class foo
{
public:
template <typename X>
void f(X);

void ff ();
};

#include "foo.tpp"


foo.tpp

template <typename X>
void foo::f(X val)
{
cout << val;
}

void foo::ff() // multiple definitions
{
cout << sizeof(*this);
}


main2.cpp

#include "foo.hpp"


main.cpp

#include "foo.hpp"

int main()
{
return 0;
}


Adding the inline keyword to the function definition seems to solve this error, though I don't want to use it because I've got other non-template member functions suffering the same issue which are way larger and are referenced in multiple parts of the code. Is there any work-around or valid way to do what I'm trying to do? Thanks in advance!

Answer

Create a third, foo.cpp file for the definitions of non-template functions that should not be inlined. The class is non-template, so you don't need to define all its member functions in the header, just the template ones.