Say I declare a template class A
in a.h
#include <iostream>
template<bool b>
class A {
public:
void print(std::ostream& out);
};
And define the print method in a.cpp
(with explicit instatiation for true
and false
)
#include "a.h"
template<bool b>
void A<b>::print(std::ostream& out) {
out << "A" << b;
}
template class A<true>;
template class A<false>;
An example main main program in main.cpp
could be
#include "a.h"
int main() {
A<true> a;
a.print(std::cout);
}
The small project above compiles just fine.
Question: If I put the explicit instantiations above the definition of the print
method (in a.cpp
), the code doesn't compile anymore, with the usual undefined reference to A<true>::print(...)
error.
#include "a.h"
template class A<true>;
template class A<false>;
template<bool b>
void A<b>::print(std::ostream& out) {
out << "A" << b;
}
Why is this the case?
Edit: Makefile to compile
main : main.o a.o
g++ main.o a.o -o main
main.o : main.cpp
g++ -c main.cpp
a.o : a.cpp
g++ -c a.cpp