0

I'm using C++17 in Visual Studio 2017. I want to execute a class method in another class method, using lambda expressions. I have done it this way so far:

void CMFCApplicationDlg::Add_text() {

    std::ofstream outfile;
    outfile.open("test.txt", std::ios_base::app);
    outfile << "text added" << std::endl;
}


void CMFCApplicationDlg::Start_adding() {

    sched.cron("0 12 * * *", [this]() { CMFCApplicationDlg::Add_text(); });
}

I think it would be better if it's possible to send a pointer of Add_text to Start_adding as a parameter and use it with lambda expressions.

How can I:

  1. Make a pointer of a class method?
  2. Send it to another method?
  3. Run it in a lambda function?

I'd appreciate it if I could get some example code.

Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
maynull
  • 1,936
  • 4
  • 26
  • 46
  • For (1) see here: [Calling C++ class methods via a function pointer](https://stackoverflow.com/questions/1485983/calling-c-class-methods-via-a-function-pointer). – Adrian Mole Dec 30 '19 at 05:38
  • See also [std::function](https://en.cppreference.com/w/cpp/utility/functional/function) Note, in MFC you can use `TRACE` for debug and testing, instead of writing to file. Or just make a simple example without MFC and external classes, use `std::cout` – Barmak Shemirani Dec 30 '19 at 15:22

1 Answers1

1

The below code should answer all your questions:

#include <iostream>

class Test {
public:
    // 2 test functions
    void print1(int i) { std::cout << "From function print1: " << i << "\n"; }
    void print2(int i) { std::cout << "From function print2: " << i << "\n"; }
    void print3(int i) { std::cout << "From function print3: " << i << "\n"; }

    // Function taking function pointer
    void test1(void (Test::* functionPointer)(int), int para) {

        std::cout << "\nFrom function test1:\n";
        (*this.*functionPointer)(para);
        std::cout << "\n";
    }

    void test2()
    {
        std::cout << "\ntest2. Call via other function\n";
        // Calling with function pointer via other function
        test1(&Test::print1, 17);

        std::cout << "\ntest2. Call via function pointer\n";
        // Define function pointer 
        void (Test::* fptr)(int) = &Test::print2;
        // Call function pointer
        (this->*fptr)(3);


        std::cout << "\ntest2. Call via lambda\n";
        // Lambda
        auto lambda = [&fptr,this](const int i) { (this->*fptr)(i); };
        // Call lambda
        lambda(42);
    }
};

If you need an addtional explantion, then anytime.

A M
  • 14,694
  • 5
  • 19
  • 44