David Levy
David Levy

Reputation: 511

function template specialization syntax for cpp file

I have a templated function declared in my .h and implemented in my .cpp:

//file.h
class FileReader{
template <class T> void Read( T *aValue );
};

//file.cpp
template<class T>
void
FileReader::Read( T *aValue )
{
    //implementation
}

To allow the implementation in my .cpp, I had

template void FileReader::Read<uint8_t>( uint8_t * );
template void FileReader::Read<uint16_t>( uint16_t * );

But trying to fix a doxygen issue, someone pointed me here that I should use

template<> void FileReader::Read<uint8_t>( uint8_t * );
template<> void FileReader::Read<uint16_t>( uint16_t * );

This indeed, fixes the doxygen issue, but it breaks my compilation at linking.

=>What is the correct syntax to specialize my function template in my .cpp and allow the function to be linked?

This other question seems to indicate that I should use my second version. But this article uses my first version.

Upvotes: 3

Views: 271

Answers (1)

Brian Bi
Brian Bi

Reputation: 119069

The correct syntax depends on what you're actually trying to do. Adding the <> is NOT just a way to fix Doxygen---it substantially changes the meaning of the program!

The following are explicit instantiation definitions:

template void FileReader::Read<uint8_t>( uint8_t * );
template void FileReader::Read<uint16_t>( uint16_t * );

They tell the compiler to instantiate the function template right then and there, and to emit symbols for the instantiations so that they can be linked to by another translation unit. This seems to be what you're actually trying to do.

The following are explicit specialization declarations:

template<> void FileReader::Read<uint8_t>( uint8_t * );
template<> void FileReader::Read<uint16_t>( uint16_t * );

They tell the compiler that you're going to define your own specializations of the template for those particular template arguments. Thus, anyone who tries to call FileReader::Read<uint8_t> will NOT instantiate the primary template that you've already defined, but rather, look for a specialized definition. It doesn't look like that's what you're trying to do, but if it were, you would actually have to define those specializations at some point.

Upvotes: 5

Related Questions