AntonioCS
AntonioCS

Reputation: 8496

C++ Passing a class method as function pointer

I have a class that has to process data from various files. I thought about creating one function that will read the specified file and then also accept a call back so that it can use that to process the line. Below is an example class to represent what I am trying to do:

#include <iostream>
#include <vector>
#include <string>


class Example
{
    std::vector<std::string> m_exampleFileData {
        "test1",
        "test2",
        "test3"
    };

public:

    void doSomethingMain(const std::string& path)
    {        
        processFile(path, doSomething);
    }


private:    
    void processFile(const std::string& filePath, void (Example::*fpProcessLine)(const std::string&) )
    { 
        for (const auto& line : m_exampleFileData) {    
            this->*fpProcessLine(line);
        }
    }

    void doSomething(const std::string& line)
    {
        std::cout << "Hello: " << line << '\n';
    }

};


int main(int argc, char** argv) {    
    const std::string filePath{"path"};
    Example ex;

    ex.doSomethingMain(filePath);
}

Compiler explorer: https://godbolt.org/z/LKoXSZ

The main issue is that no matter what I do I can't seem to be able to pass the function properly to processFile. Is there a way to do this in C++? How do I go about this?

Upvotes: 2

Views: 1459

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118292

You need to spell things out explicitly, in this situation:

    processFile(path, &Example::doSomething);

Furthermore, you also need to slap on an extra pair of parenthesis, due to operator precedence:

         (this->*fpProcessLine)(line);

Upvotes: 4

Related Questions