C++ C++;模板类来包装任意函数
我想包装任何输入/输出类型的函数。下面我尝试使用C++模板。p>C++ C++;模板类来包装任意函数,c++,templates,C++,Templates,我想包装任何输入/输出类型的函数。下面我尝试使用C++模板。p> 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&
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);
}
为什么C++编译器无法推断TestFoeType的类型?我怎样才能修好它?谢谢还有,有没有不那么尴尬的方法呢?我明白了。还有什么更明确的方法?为什么C++编译器无法推断出TestFoeType的类型?你可以用<代码>测试函数< /C> >或<代码>测试函数< /C> >代替<代码> Auto <代码>。就我个人而言,我觉得
auto
更容易输入。@zell,当概念TS进入到语言中时,语法应该可以用来推断模板参数,而其余的仍然是显式的。
TestFunction<> testFunc = createTestFunction(foo);
TestFunction<> testFunc = createTestFunction(foo);
auto testFunc = createTestFunction(foo);