2012-05-12 25 views
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); 

回答

1

您的call_ads模板需要一個類型參數。 addone不是一種類型,它是一種功能。您可以專門爲call_adds專門設計類型,如int(int),但不適用於該類型的單個功能。

您可以創建一個函數模板與非類型模板參數:

template <int F(int)> 
void call_adds(int n) 
{ 
    cout << F(n) << endl; 
} 

,並專注它:

template<> void call_adds<addtwo> (int n) { ... } 

注意call_adds不具有定時功能參數更多,只有一個模板參數。

只要聲明在應該出現的地方是可見的,編譯器並不在乎您是在頭文件還是在源文件中聲明某些內容。

+0

不知道我完全理解答案。請允許我確認:因爲我無法將'addone'作爲類型參數傳遞,所以如果我不想將頭文件中的函數模板定義,我必須使用模板參數作爲您提出的答案? –

+0

此外,我必須將最後一行改爲'template'而不是'template <>'以使代碼正常工作。 –

+0

做了一些閱讀後,看起來像你建議做一個模板專業化。我不認爲我需要那樣做。我只需要'Explicit instantiation' [http://www.cplusplus.com/articles/1C75fSEw/]。 –

相關問題