Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 278
Hello World Avatar asked Aug 05 '16 19:08

Hello World


1 Answers

Create a third, foo.cpp file for the definitions of non-template functions that are not declared as inline. The class is non-template, so you don't need to define all its member functions in the header, just the template ones (or maybe not).

like image 111
LogicStuff Avatar answered Dec 07 '22 16:12

LogicStuff