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 <>?我該如何解決它?謝謝。另外,有沒有一個尷尬的方式來做到這一點?
我明白了。有更明確的方法嗎? – zell
另外,爲什麼C++編譯器無法推斷TestFunction <>的類型? – zell
你可以用'TestFunction'替換'auto'。 –
Jarod42