I am trying to learn C++ myself by reading a book and do exercise from that book.
Now I am trying to declare an instance of function template inside the .cpp file. I know that I can declare/define that function template in header file, but I am still curious about how to do that inside the .cpp file.
Here is piece of code which is trivial but demonstrate my problem:
// temp_func.h
#ifndef GUARD_temp_func
#define GUARD_temp_func
#include <iostream>
using std::cout; using std::endl;
int addone(int);
int addtwo(int);
template<typename F>
void call_adds(int, F);
#endif
Header file
// temp_func.cpp
#include "temp_func.h"
using std::cout; using std::endl;
int addone(int n)
{
return n + 1;
}
int addtwo(int n)
{
return n + 2;
}
template<typename F>
void call_adds(int n, F f)
{
cout << f(n) << endl;
}
template void call_adds<addone>(int n, F addone);
.cpp file, and obviously the last line doesn’t work.
Edit:
Based on solutions provided by n.m.
template<int F(int)>
void call_adds(int n)
{
cout << F(n) << endl;
}
template void call_adds<addtwo>(int);
template void call_adds<addone>(int);
Your
call_adstemplate requires a type parameter.addoneis not a type, it’s a function. You can specializecall_addsfor a type likeint(int), but not for individual functions of that type.You can create a function template with a non-type template parameter:
and specialize it:
Note that
call_addsdoesn’t have a regular function parameter any more, only a template parameter.The compiler doesn’t really care whether you declare something in a header file or in a source file, as long as the declaration is visible where is should be.