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!
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With