I have a function template declared in an header file. This function is an archiver which is supposed to support several other types (classes) implemented through the project. The idea is to have a base template declaration which each class then specialises to its own types.
// Archiver.h
template <class T> void archive(Archiver & archiver, const T & obj);
This method does not have an implementation. Now I create a class (say, Header
) and I want it to be archivable. As such, it is my intent to specialise the method. Here's what I have now:
// Header.h
extern template void archive(Archiver & archiver, const Header & obj);
I declare the function as extern
because I implement it in the .cpp file
// Header.cpp
template <> void archive(Archiver & archiver, const Header & obj)
{
// Code here
}
This gives specialization after instantiation
. I've tried other combinations as well:
- Implementing directly in the header file, as is usually recommended for templates: I get "multiple definition"
- Implementation in the .cpp file without a declaration on the header: I get
undefined reference
when calling the method from another compilation unit
So what is the correct of implementing this?
Edit:
Initially I decided to go with templates because of the inverse process, unarchiving. Basically I could write unarchive<Header>()
instead of unarchive_header()
which seemed more appropriate.
I believe I should also mention that I'm compiling this using Android Studio and the Gradle build system, which is why I'm using gcc and not g++. I also gave gcc the following compiler flags:
-std=gnu++11 -fexceptions -fpermissive -lstdc++
-fpermissive
was an act of despair.