如何通过迭代器通过指针调用函数
How to call a function by pointer by iterator?
我已经声明了一个全局类型:
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
相关文章:
- 为什么使用 "this" 指针调用派生成员函数?
- 当使用通配符和null指针调用函数时,对输出的说明
- Visual c ++,使用字符串引用/指针调用 dll 函数
- 使用基类指针调用基类的值构造函数的语法是什么?
- 是否可以使用函数指针调用虚拟析构函数?
- 使用C++指针调用 python 函数
- 如何使用接口指针调用方法,该指针是其具体类的一部分,而不是接口的一部分
- 是否可以使用非常量指针调用非常量函数,以及当两个unique_ptrs指向同一个对象时程序的行为方式?
- 在将派生类指针类型转换为派生类指针后,从基类指针调用派生类函数
- 通过指针调用模板类成员函数 [为什么这是有效的 c++]?
- 从带有参数的基函数指针调用基方法
- 使用唯一指针调用函数会使我的程序崩溃
- C++::在构造函数退出之前通过指针调用成员函数
- 有没有办法在没有虚拟的情况下使用基类指针调用派生类函数
- 什么时候用指针调用C++类构造函数
- C++ - 使用变量指针调用函数
- 为什么我可以通过野生指针调用成员函数
- 从指针调用方法时出现分段错误
- 为什么使用指向函数的指针调用虚函数时不需要指针"this"?
- C++ abort() 在函数内的抽象类对象指针调用上