2015-05-09 40 views
2

我想包裝任何輸入/輸出類型的函數。下面我嘗試使用C++模板。C++模板類來包裝任何函數

double foo(double x){return x*x;} 

template <typename funct> 
class TestFunction{ 
public: 
    TestFunction(const funct& userFunc): f(userFunc){} 

private: 
    const funct& f; 
}; 


template <typename funct> 
TestFunction<funct> createTestFunction(const funct& f){ 
    return TestFunction<funct>(f); 
} 


int main(){ 
    TestFunction<> testFunc=createTestFunction(foo); 

} 

編譯這個節目給我的錯誤信息:

too few template arguments for class template 'TestFunction' 

爲什麼C++編譯器無法推斷類型TestFunction <>?我該如何解決它?謝謝。另外,有沒有一個尷尬的方式來做到這一點?

回答

3
TestFunction<> testFunc = createTestFunction(foo); 

應該

auto testFunc = createTestFunction(foo); 
+0

我明白了。有更明確的方法嗎? – zell

+0

另外,爲什麼C++編譯器無法推斷TestFunction <>的類型? – zell

+0

你可以用'TestFunction '替換'auto'。 – Jarod42