JuliusCaesar
JuliusCaesar

Reputation: 351

Issue with extern templates c++

I'm using C++ and I'm having struggle with extern templates. In opposite to C# the whole template implementation is really nasty in C++ :(

template_test.hpp

template<class T>
class CFoo {
        public:
            T Foo_Func(const T& test);
};

template_test.cpp

#include "Template_Test.hpp"
    template<class T>
    T CFoo<T>::Foo_Func(const T& test)
    {
            return test;
    }

template_test2.hpp

#include "Template_Test.hpp"
extern template class CFoo<int>;
int Template_Tests();

template_test2.cpp

#include "Template_Test2.hpp"
int Template_Tests()
{

    CFoo<int> foo_instance;

    //this causes an undefined reference
    int res = foo_instance.Foo_Func(1);

    return res;
}

why does the linker not find my function. I thought extern templates worked the same why as extern variables. (Put extern int test; in the header file and int test = 0 in the source file.)

thanks for your support:)

Upvotes: 1

Views: 121

Answers (1)

Coral Kashri
Coral Kashri

Reputation: 3506

Solution 1

One way to solve this issue is to implements the template class's function without function's definitions. in this case:

template<class T>
class CFoo {
public:
    T Foo_Func(const T& test) {
        return test;
    }
};

And then, you don't even need the extern part. I aware that your programmer sense keep telling you to avoid from this, and always to separate between your class functions' definitions, and their implementation- but in template case in c++, it's the easiest solution for this language's huge problem.

An important thing that you need to know- there is a big different between the solutions for this issue between differnt IDEs, but this easy solution works in most of them (if not always).

Solution 2

Another option, if you still want to separate the implementations from the definitions you can include the .cpp file, as well as the .hpp/.h file:

template_test2.hpp

#include "Template_Test.hpp"
#include "Template_Test.cpp"
/*extern template class CFoo<int>;*/ // Again, you don't need this extern
int Template_Tests();

Solution 3

It is the closest way to the way that you tried. in the end of template_test.cpp file, add the following line:

template class CFoo<int>;

and remove the line extern template class CFoo<int>; from the template_test2.hpp file.

I hope that you will find it helping, Korel.

Upvotes: 1

Related Questions