zell
zell

Reputation: 10204

C++ template class to wrap a whatever function

I want to wrap a function of whatever input/output types. Below I try to use the C++ template.

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);

}

Compiling this program gives me the error message:

too few template arguments for class template 'TestFunction'

Why C++ compiler fails to infer the type for TestFunction<>? How can I fix it? Thanks. Also, is there a less awkward way to do this?

Upvotes: 2

Views: 166

Answers (1)

Jarod42
Jarod42

Reputation: 217085

TestFunction<> testFunc = createTestFunction(foo);

should be

auto testFunc = createTestFunction(foo);

Upvotes: 3

Related Questions