vendredi 31 juillet 2015

How to initialize class member std::function?

I am trying to create a class with an std::function member:

class Widget {
public:
  std::function<int(double)> call_foo;

  Widget(std::function<int(double)> call_func)
    : call_foo(call_func)
  {};

};

However, when I try to initialize the class my code fails because 'function' in namespace 'std' does not name a template type

const int f(double x){
  if(x > 5.0){
    return 22;
  }
  return 17;
}

int main()
{
  std::function<int(double)> f1 = f;
  Widget p(f1);

}

The full set of errors is below:

widget.cpp:5:8: error: ‘function’ in namespace ‘std’ does not name a template type
   std::function<int(double)> call_foo;
        ^
widget.cpp:8:23: error: expected ‘)’ before ‘<’ token
   Widget(std::function<int(double)> call_func)
                       ^
widget.cpp: In function ‘int main()’:
widget.cpp:23:3: error: ‘function’ is not a member of ‘std’
   std::function<int(double)> f1 = f;
   ^
widget.cpp:23:17: error: expected primary-expression before ‘int’
   std::function<int(double)> f1 = f;
                 ^
widget.cpp:24:12: error: ‘f1’ was not declared in this scope
   Widget p(f1);

I also tried initializing with f directly, but this produces an error as well. What's wrong with my syntax?

Aucun commentaire:

Enregistrer un commentaire