2015-05-09 41 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