vkubicki
vkubicki

Reputation: 1124

Specialization of member function of a template class in C++

I would like to create a template class foo, and have one of its member function test() be specialized according to the template type of foo. M first attempt was to include the code in the header file defining foo:

template<typename Type>
class foo
{
    foo()
    ~foo()
    test()
};

template<>
foo<float>::test()
{ code ... };

The problem is that if I compile and link multiple files using this header, I get an error of multiple definition.

I also tried to declare the specialization in the header, so the compiler knows it should not generate the templated code. I then put the specialized definition in a separate C++ file to be compiled. The header then looked like:

template<typename Type>
class foo
{
    foo()
    ~foo()
    test()
};

template<>
foo<float>::test();

But I then got an undefined reference error.

How should I organize the declaration and definition of the specialized member function ?

Upvotes: 2

Views: 121

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409432

Put the declaration in the header file, and the definition in a source file.

Since the function is fully specified by the declaration, the definition can be in any translation unit. linked with the application.

Or make the function definition inline in the header file.

Upvotes: 4

Related Questions