Pass a class member function as a function parameter

前端 未结 3 1607
慢半拍i
慢半拍i 2020-12-31 19:34

I have 2 C++ Class questions:

The 1st question is: How can I make it so I can pass a class member function as a parameter in another function &

3条回答
  •  隐瞒了意图╮
    2020-12-31 20:19

    Here is what you want, where X is your class, T is the return of your method and Args are the arguments your function receives.

    If your method takes no args, just don't pass them as in test1 and test2.

    If your method has void return, than erase the T template and write void where T was on the methods signature.

    If you have link errors, remember to define doMember and doStatic in your .h file. By define I mean write the entire function, not just its signature. That's due to template issues.

    #include 
    
    class DebuggingManager
    {
    
    private:
    
        std::string testLog;
    
        bool test1()
        {
            // run test & return whether it passed or failed
            return true;
        }
    
        static bool test2()
        {
            return false;
        }
    
        int test3(int a, int b)
        {
            return a + b;
        }
    
        static int test4(int a, int b)
        {
            return a - b;
        }
    
        void catalogueTest(std::string testName, int result)
        {
            testLog += "Status of " + testName + ": " + std::to_string(result) + "\n";
        }
    
        // How can I call a member function?
        template 
        T doMember(X* obj, T(X::* func)(Args...), Args... args)
        {
            return (obj->*func)(args...);
        }
    
        // How can I call a static function?
        template 
        T doStatic(T func(Args...), Args... args)
        {
            return func(args...);
        }
    
    public:
    
        // how do I pass a member function or a static function as a parameter in another function 
        void runTests()
        {
            catalogueTest("Test of member functin", doMember(this, &DebuggingManager::test1));
            catalogueTest("Test of member functin", doMember(this, &DebuggingManager::test3, 10, 20));
            catalogueTest("Test of static functin", doStatic(DebuggingManager::test2));
            catalogueTest("Test of static functin", doStatic(DebuggingManager::test4, 10, 20));
            std::cout << testLog << std::endl;
        }
    
    };
    

提交回复
热议问题