0
我想通過閱讀一本書來學習C++自己,並從那本書做練習。如何聲明將函數作爲參數傳遞給.cpp文件中的函數模板?
現在我試圖在.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文件,顯然最後一行不起作用。
編輯: 基於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);
不知道我完全理解答案。請允許我確認:因爲我無法將'addone'作爲類型參數傳遞,所以如果我不想將頭文件中的函數模板定義,我必須使用模板參數作爲您提出的答案? –
此外,我必須將最後一行改爲'template'而不是'template <>'以使代碼正常工作。 –
做了一些閱讀後,看起來像你建議做一個模板專業化。我不認爲我需要那樣做。我只需要'Explicit instantiation' [http://www.cplusplus.com/articles/1C75fSEw/]。 –