0

One of my class member function needs other member functions as arguments. I learnt that the member function pointer or lambda expression can pass the member function to another member function. I did this in my class declaration:

class A
{
public:
void run();

private:
double objfun1();
double objfun2();
.... // and other object function added here
template <typename Callable>
fun_caller(Callable obj_call);

};

When I need to pass different object functions to fun_caller in the public function A::run(), I first define the lambda expression:

void run()
{
... //some code blocks
auto obj_call = [this](){return objfun1();}; 
fun_caller(obj_call);
... // some code blocks
}

The compiler reports error.

error C2297: '->*': illegal, right operand has type 'Callable'

What's wrong with my lambda expression? Thank you very much!!

7
  • 3
    The compiler reports error. Which error? Commented Jul 2, 2022 at 5:58
  • 1
    You can store the lambda in a std::function and use std::function as the argument type. Commented Jul 2, 2022 at 6:00
  • error C2297: '->*': illegal, right operand has type 'Callable' Commented Jul 2, 2022 at 6:01
  • In the code above there's a semicolon missing behind the return statement in your lambda. Commented Jul 2, 2022 at 6:02
  • 2
    There is no ->* in the code you have shown. Commented Jul 2, 2022 at 6:05

1 Answer 1

3

This works:

#include <iostream>

class A
{
public:
    void run();

private:
    double objfun1(){ return 1.; }
    double objfun2(){ return 2.; }

    template <typename Callable>
    void fun_caller(Callable obj_call){
        std::cout << "called: " << obj_call() << "\n";
    }
};

void A::run(){
    auto obj_call = [this](){return objfun1();}; 
    fun_caller(obj_call);
}

int main(){
    A obj;
    obj.run();
}

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

2 Comments

Thank you infinitezero!! I found I wrote a stupid bug in the fun_call(). Now this question could be closed.
@YS_Jin as a good practice, it's useful to write a Minimal Working Example. Not only can you post it here, often enough you can then find the mistake on your own :)

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.