Without optimization flags, the following code compiles fine, but with -O1
both g++ and clang++ throw undefined reference to 'void Foo::Fooify<int>(int)'
Adding an explicit instantiation in foo.cpp
solves the issue, but that seems redundant to me after an implicit instantiation. Is it really necessary to do that or are the compiler optimizations at fault here?
//foo.h
struct Foo {
template <class T>
void Fooify(T);
void UseFooifyForInt();
};
//foo.cpp
#include foo.h
template <class T>
void Foo::Fooify(T) {}
void Foo::UseFooifyForInt() {
Fooify(5);
}
//main.cpp
#include foo.h
int main() {
Foo f{};
f.Fooify(42);
}
This question is currently marked as a duplicate of Why can templates only be implemented in the header file?, but one of the solutions given there is to explicitly instantiate the templates in the .cpp file (in my case that would be foo.cpp
. I am wondering why an implicit instantiation does not work for this use case.