W. Verbeke
W. Verbeke

Reputation: 355

Passing non-static member function as argument to member function

I am trying to pass a non-static member function of a class as an argument to another member function that takes a function reference. The code I currently have can be illustrated as:

bool someClass::baseFunction( unsigned argument, bool (&argumentFunction)(unsigned) ) const{
    ...
    ... use argumentFunction(argument) somehow...
    ...
}

bool someClass::anotherFunction(unsigned) const{
    ...
}

bool someClass::finalFunction(unsigned argument) const{
    return baseFunction(argument, anotherFunction);
}

However this prompts the compiler error

"invalid use of non-static member function"

, and I understand this is because the function I pass as an argument inside "finalFunction" is non-static. However is there any other way to pass a non-static member function as an argument in the code I have shown here?

Upvotes: 0

Views: 1920

Answers (3)

Kerrek SB
Kerrek SB

Reputation: 477040

If you're going to call the member function on the same object as the calling member function's object, then a simple pointer-to-member should do the trick:

bool someClass::anotherFunction(unsigned int) { /* ... */ }

bool someClass::baseFunction(
    unsigned int argument,
    bool (someClass::* mf)(unsigned int) const) const {
  return (this->*mf)(argument);
}

bool someClass::finalFunction(unsigned argument) {
  return baseFunction(argument, &someClass::anotherFunction);
}

Upvotes: 1

Useless
Useless

Reputation: 67733

If you only want to use non-static methods of a single class, just change the type of the argument function parameter to a member function pointer

bool someClass::baseFunction(unsigned argument,
                             bool (someClass::*argumentFunction)(unsigned))
{
    // use argumentFunction(argument) somehow...
    return (this->*argumentFunction)(argument);
}

Note that I've changed baseFunction to be non-const, since you have it invoking a non-const member function.

bool someClass::finalFunction(unsigned argument){
    return baseFunction(argument, &someClass::anotherFunction);
}

Upvotes: 0

SergeyA
SergeyA

Reputation: 62563

One way to achieve desired functionality would be to use std::function instead of the member function pointer. It would like something like this:

bool someClass::baseFunction(unsigned argument, std::function<bool (unsigned) const> argumentFunction) const {
    argumentFunction(argument);
}

bool someClass::anotherFunction(unsigned){
    /// ...
}

bool someClass::finalFunction(unsigned argument) {
    return baseFunction(argument, [this](unsigned arg){ this->anotherFunction(arg); });
}

Note, that in your case, argument is always the same, so you can capture it as well in lambda and do not pass argument into baseFunction at all.

Upvotes: 0

Related Questions