How can I declare template function in header file and define in source file?
// foo.h
template<typename T>
bool foo();
// foo.cpp
template<typename T>
bool foo()
{
return false;
}
// main.cpp
bool bar = foo<int>();
I've got this so far. It compiles, but fails at linker: "undefined reference to `bool foo<int>()`"
You can't. But there is a workaround if you really want seperate files:
Foo.tpp
template<typename T> void foo()
{
}
Foo.hpp
#ifndef FOO_HPP_
#define FOO_HPP_
template<typename T>
void foo();
#include "Foo.tpp";
#endif
main.cpp
#include "Foo.hpp"
int main()
{
foo<int>();
}
Basically you put the implementation in a seperate file that is not recognised by the compiler, and you include that at the end of your header.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With