YS_Jin
YS_Jin

Reputation: 55

Using lambda expression as function argument

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!!

Upvotes: 0

Views: 201

Answers (1)

infinitezero
infinitezero

Reputation: 2077

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();
}

Upvotes: 3

Related Questions