1

I have an issue that I'm not sure how to get around.

I am using a library whose instances of the class are constructed by being passed references to a few functions.

void func_on_enter() {...}
void func() {...}
void func_on_exit(){...}

State state_a(&func_on_enter, &func, &func_on_exit);

I am writing a class that contains an instance of this class, and as such have attempted something like this:

class MyClass{
private:
  void func_on_enter() {...}
  void func() {...}
  void func_on_exit(){...}

  State _state_a;

public:
  MyClass() : _state_a(&func_on_enter, &func, &func_on_exit) {}
};

I get the error "ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function. Say '&MyClass::_func_on_enter'" (and the same for the other two methods obviously). The compiler helpfully provides a solution, which I tried.

However the compiler then reminds me that there is no matching function for a call to 'State::State(void (MyClass::*)(), void (MyClass::*)(), (MyClass::*)())' and that it has no known conversion from 'void (MyClass::*)()' to 'void(*)()'.

I tried reading up on similar questions about this error but can't seem to find a solution that I both understand and can help in this situation.

I considered trying to add an overload constructor to State, but this seems absurd to do on a class by class case, considering that I could be calling it from any other class.

I also thought for a while that I could just make the functions static (as they're the same for all instances of MyClass), but I quickly remembered that they would then be unable to use non-static member variables of MyClass.

Is there perhaps a way that I can provide a conversion or provide the pointers for the State constructor in another way?

I could really do with some help on this, as I'm quite stuck for ideas on how to move forward. Any help or hints would be greatly appreciated!

4
  • 1
    Are you in control of the State class? If you are, switch from raw void(*)() pointers to std::function<void()> or template State on the type of the callbacks. If you're not, what you want may be difficult to impossible. Apr 4, 2019 at 10:42
  • A simple solution (which may not be applicable to you) is just to make func etc static.
    – john
    Apr 4, 2019 at 10:48
  • @MilesBudnek I can be in control of the State class - I've already forked the library it comes from to add more features. I suppose I need to remind myself of the inner workings of State to see if this would require me to rewrite (or template) the whole class or whether I can get away with overloading the constructor to accept std::function<void()>. I'm not very familiar with std::function, am I understanding correctly that they can be used similarly to pointers to indirectly call a function? If so, I can see this being the solution!
    – JRVeale
    Apr 4, 2019 at 11:29
  • @john definitely could be helpful for others, but not in my case unfortunately
    – JRVeale
    Apr 4, 2019 at 11:29

2 Answers 2

2

Pointers to non-static member functions cannot be converted to plain function pointers. A void (MyClass::*)() requires a MyClass object to operate on. Raw pointers can't hold any sort of state though, so there's no way for a void(*)() to store the information about which MyClass object to operate on.

Luckily, the standard library has a class template designed for just this purpose: std::function. std::function is a more-or-less drop-in replacement for raw function pointers, but it can hold any type of callable object that's compatible with a given signature. That means it can hold the state required to call back to a specific instance of a class:

class State {
private:
  std::function<void()> on_enter;
  std::function<void()> func;
  std::function<void()> on_exit;

public:
  State(std::function<void()> on_enter, std::function<void()> func, std::function<void()> on_exit)
    : on_enter{std::move(on_enter)},
      func{std::move(func)},
      on_exit{std::move(on_exit)}
  {}

  void do_something() {
    on_enter();
    // stuff
    func();
    // more stuff
    on_exit();
  }
};

class MyClass {
private:
  void func_on_enter() {}
  void func() {}
  void func_on_exit(){}

  State state_a;

public:
  MyClass()
    : state_a([this]() { func_on_enter(); },
              [this]() { func(); },
              [this]() { func_on_exit(); })
  {}
};

Live Demo

Here, instead of passing pointers to your member functions directly, I've wrapped them in lambdas that capture the this pointer of the object to be called back. Now the State object is able to call those members, and they know which instance of MyClass to operate on.

Be careful about object lifetime though. Since state_a holds pointers back to its MyClass instance, you'll need to ensure MyClass's copy/move constructor and assignment operators do the right thing. The default implementations provided by the compiler aren't sufficient.

5
  • I assume hat one must ensure that the lifetime of the given State instance does not exceed the lifetime of the MyClass instance it was initialized with. (In the given use case where the State is a member of the given MyClass this is guarenteed.)-- Very nice solution. Apr 4, 2019 at 12:09
  • @PeterA.Schneider It's not guaranteed for copies of MyClass though. The State of the copy will refer to the source of the copy, whose lifetime may have ended.
    – eerorika
    Apr 4, 2019 at 12:19
  • A few questions @MilesBudnek: 1. Looking through your example, the only part I don't understand are the lambdas. How do they produce the std::function<void()> for the constructor of state_a? Or does the compiler implicitly convert them into std::function<void()>s? 2. If I want, for example, state_a to do nothing in place of func(), my previous State could be initiated with NULL wherever I didn't want a function call. Can I do this with this method?
    – JRVeale
    Apr 4, 2019 at 23:12
  • @JRVeale 1. std::function<void()> is implicitly constructible from any callable object that takes no parameters and returns void, including lambdas. 2. std::function can hold no callable. Use either the no-arg constructor or the one that accepts nullptr. It's also contextually convertible to bool, so you can check if it holds a callable with something like if (func) { func(); } just like you would a raw function pointer. Apr 4, 2019 at 23:39
  • Brilliant, thank you. I'm looking forward to implementing this now
    – JRVeale
    Apr 5, 2019 at 22:48
1
void func_on_enter() {...}
void func() {...}
void func_on_exit(){...}

State state_a(&func_on_enter, &func, &func_on_exit);

For this to work, the constructor of State must be accepting of function pointers of type void(*)().

_state_a(&MyClass::func_on_enter, &MyClass::func, &MyClass::func_on_exit)

For this to work, the constructor of State must be accepting of member function pointers of type void (MyClass::*)(). Member function pointers are not convertible to function pointers.

You could change the constructor of State to accept member function pointers of correct type.

7
  • This would work yes. As I'm likely to use State within other classes too I think using std::function<void()> in State (ss per @MilesBudnik 's suggestion) will be the best way forward to allow State to be called in any class (and not just MyClass)
    – JRVeale
    Apr 4, 2019 at 11:33
  • What's the difference between case 1 and case 2? Is the qualification in case 2 not redundant within MyClass? Apr 4, 2019 at 11:46
  • I think this fundamentally disregards the design of State. It is supposed to work with a freestanding function. Introducing a dependency to e.g. MyClass (and how many others?) does not seem to be a good design decision, even if the OP can change State. Apr 4, 2019 at 11:48
  • @PeterA.Schneider 1. The difference is that functions in case 1 are not non-static member functions. Functions in case 2 are non-static member functions. 2. The qualification is not redundant within MyClass. 3. The intended design of State has not been stated (until the comment to my answer which touches on a bit), except that OP wishes to pass non-static member functions into the constructor. It is sometimes OK to have dependencies between classes, and some classes can be intended to be used only with another class.
    – eerorika
    Apr 4, 2019 at 11:56
  • 1
    Oh, sorry, I see now that the first quoted code was just the freestanding function example. Of course those cannot be qualified with a class name, and their type is indeed void(*)().-- With respect to "the first example shows how the class works": it works that way because it was designed that way -- without a dependency to MyClass. I understand that the OP would find it convenient to pass member function pointers, but by doing that a dpendency is introduced which was apparently not planned in the original design. State is a generic name; it's not MyClass::State. Apr 4, 2019 at 12:04

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.