1

I have started trying to learn std::function after reading Scott Meyers Effective C++. I made the following sample program to give a std::function object to a class

#include <iostream>
#include <string>
#include <functional>

class FlyBehaviour
{
  public :
  void fly()
  {
    std::cout<<"Flying";
    /* Work Here */
  }
};

typedef std::function<void(const FlyBehaviour&)> FlyFunc;

class Duck
{
  public :
  Duck(FlyFunc flyFunc) : _flyFunc(flyFunc){}

  private :

  FlyFunc _flyFunc;
};

int main()
{
  Duck(&FlyBehaviour::fly);
}

Compiling the above code gives me the following error

error: invalid use of qualified-name 'FlyBehaviour::fly'

On research, most of the internet points to using std::bind/boost::bind as a solution. Can someone please tell me how to apply it, especially where do I need to declare the object to which function is binded?

1
  • What solutions did your research reveal? You're really close but this has been asked so many times... "where do I need to declare the object" Wherever you like? Commented Jul 6, 2015 at 23:42

1 Answer 1

2

You need to either bind a FlyBehaviour object to the std::function or supply a FlyBehavior when calling the function. Here is an example of the former (note that I changed the typedef!):

#include <iostream>
#include <string>
#include <functional>

class FlyBehaviour
{
  public :
  void fly()
  {
    std::cout<<"Flying";
    /* Work Here */
  }
};

typedef std::function<void()> FlyFunc;

class Duck
{
  public :
  Duck(FlyFunc flyFunc) : _flyFunc(flyFunc){}
  void run() {_flyFunc();}

  private :

  FlyFunc _flyFunc;
};

int main()
{
    FlyBehaviour f;
  Duck d(std::bind(&FlyBehaviour::fly, f));
  d.run();

Here, FlyBehaviour::fly's signature is void(FlyBehaviour&), but I used std::bind to bind a FlyBehaviour object to the first argument, making it a void() instead.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot for the answer. In my earlier typedef, was my signature then void (FlyBehaviour&, FlyBehaviour&) ?
No, your original typedef would work, but you would need to pass a FlyBehaviour object to call the function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.