I want to write the definition of a templated function in the .cpp
file, instead of it being in the header.
Let's take this simple example:
// func.h
template <class T>
void print_message(T func) {
func();
}
// main.cpp
#include <iostream>
#include "func.h"
void say_hello() {
std::cout << "hello" << std::endl;
}
int main(int argc, char* argv[]) {
print_message(say_hello);
return 0;
}
How do I template instantiate the print_message
function explicitly in the .cpp
file, along the lines of how it is described here.
I tried the following code snippet but I get this error: explicit instantiation of 'print_message' does not refer to a function template, variable template, member function, member class, or static data member
.
// func.h
template <class T>
void print_message(T func) {
func();
}
// main.cpp
#include <iostream>
#include "func.h"
void say_hello() {
std::cout << "hello" << std::endl;
}
template void print_message<say_hello>(say_hello func);
int main(int argc, char* argv[]) {
print_message(say_hello);
return 0;
}