简体   繁体   English

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

[英]How to call a function by pointer by iterator?

I have declared a global type: 我已经声明了一个全局类型:

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

then I need to use it in my function: 然后我需要在我的函数中使用它:

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?

}

Problem is to call function by pointer using iterator of std::map. 问题是使用std :: map的迭代器通过指针调用函数。 How to call that function? 如何调用该函数?

I suppose all will work fine if I declare "it" as a global variable and call smth like that: 我想如果我将“ it”声明为全局变量并像这样调用smth,那么一切都会正常工作:

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

but I need to call that function using a local variable. 但是我需要使用局部变量来调用该函数。

FunctionPtr is a member function pointer, so it needs to be called on an object. FunctionPtr是成员函数指针,因此需要在对象上调用它。 Using the pointer-to-member binding operator .* : 使用指针到成员的绑定运算符.*

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

The member function needs to be associated with an instance. 成员函数需要与实例关联。

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

or you can use the current object 或者您可以使用当前对象

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

Also your testFunc needs to take a string parameter. 另外,您的testFunc需要采用字符串参数。

The problem is that a member function needs an object to be applied on. 问题在于成员函数需要一个对象被应用。

One way to do this is with function objects: 一种实现方法是使用函数对象:

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

By the way, in your code sample, you should correct the signature of the test function to: 顺便说一句,在代码示例中,您应该将测试函数的签名更正为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM