如何通过迭代器通过指针调用函数

How to call a function by pointer by iterator?

本文关键字:指针 调用 函数 何通过 迭代器      更新时间:2023-10-16

我已经声明了一个全局类型:

typedef void ( MyClass::*FunctionPtr ) ( std::string );

那么我需要在我的函数中使用它:

void MyClass::testFunc() {
}
void MyClass::myFunction() {
    std::map < std::string, FunctionPtr > ptrsMap;
    ptrsMap[ "first" ] = &MyClass::testFunc;
    std::map < std::string, FunctionPtr >::iterator it;
    it = ptrsMap.begin();
    ( *it->second ) ( "param" );    // How to call this function?
}

问题是使用 std::map 的迭代器通过指针调用函数。如何调用该函数?

我想如果我将"it"声明为全局变量并像这样调用 smth,一切都会正常工作:

( this->*it->second ) ( "param" );

但我需要使用局部变量调用该函数。

成员函数需要与实例相关联。

    MyClass k;
    (k.*it->second)("param");

或者您可以使用当前对象

(*this.*it->second)("param");

此外,您的testFunc需要采用字符串参数。

FunctionPtr是一个成员函数指针,因此需要在对象上调用它。使用指向成员的指针绑定运算符.*

MyClass object;
...
(object.*it->second)("param")

问题是成员函数需要一个对象来应用。

一种方法是使用函数对象:

auto f = std::bind(it->second, this, std::placeholders::_1);  // first bind is for object
f (std::string("param"));    // How to call this function?

顺便说一下,在代码示例中,应将测试函数的签名更正为:

void MyClass::testFunc(std::string)  //  FunctionPtr requires a string argument