C 模板类包装任何功能

C++ template class to wrap a whatever function

本文关键字:任何 功能 包装      更新时间:2023-10-16

我想包含任何输入/输出类型的函数。在下面,我尝试使用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 编译器无法推断用于测试功能的类型&lt;>?我该如何修复?谢谢。另外,是否有不太尴尬的方法?

TestFunction<> testFunc = createTestFunction(foo);

应该是

auto testFunc = createTestFunction(foo);