私は本を読んで C++ を自分で学び、その本から演習をしようとしています。
今、.cpp ファイル内で関数テンプレートのインスタンスを宣言しようとしています。その関数テンプレートをヘッダー ファイルで宣言/定義できることはわかっていますが、.cpp ファイル内でそれを行う方法についてはまだ興味があります。
これは些細なコードですが、私の問題を示しています。
// 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
ヘッダーファイル
// 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 ファイルであり、明らかに最後の行は機能しません。
編集: nmが提供するソリューションに基づく
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);