前言
类成员函数指针(member function pointer),是C++语言的一类指针数据类型,用于存储一个指定类具有给定的形参列表与返回值类型的成员函数的访问信息。
基本上要注意的有两点:
-
函数指针赋值要使用 & 。( 与静态成员函数或自由函数不同,非静态成员函数不会隐式转换为成员函数指针(this)。)
-
使用
.*(实例对象)
或者->*(实例对象指针)
调用类成员函数指针所指向的函数
函数名可以作为函数的地址,但这是有前提条件的,从函数到指针的隐式转换是函数名在表达式中的行为,这个转换仅在表达式中才会发生,这只是函数名众多性质中的一个,而非本质,函数名的本质是函数实体的代表。
而C++规定非静态成员函数的左值不可获得,因此非静态成员函数不存在隐式左值转换, 即不存在像常规函数那样的从函数到指针的隐式转换,所以必须在非静态成员函数前使用&操作符才能获得地址。
std::mem_fn
函数模板std::mem_fn
为指向成员的指针生成包装器对象,该包装器对象可以存储,复制和调用指向member的指针。
调用时,可以使用对象的引用和指针(包括智能指针)std::mem_fn
。
示例:
#include <iostream>
#include <functional>
struct Foo {
void display_greeting() {
std::cout << "Hello, world.\n";
}
void display_number(int i) {
std::cout << "number: " << i << '\n';
}
int data = 7;
};
int main() {
Foo* foo = new Foo;
void (Foo::*greeting)(void) = &Foo::display_greeting;
(foo->*greeting)(); // 类成员函数指针调用,灵活性差
void (Foo::*display)(int) = &Foo::display_number;
(foo->*display)(42);
int Foo::*num = &Foo::data;
std::cout << "data: " << foo->*num << '\n';;
Foo f;
std::_Mem_fn<void(Foo::*)()> greet = std::mem_fn(&Foo::display_greeting);
greet(f); // 将对象作为参数传入,可复用
std::_Mem_fn<void(Foo::*)(int)> print_num = std::mem_fn(&Foo::display_number);
print_num(f, 42);
std::_Mem_fn<int Foo::* > access_data = std::mem_fn(&Foo::data);
std::cout << "data: " << access_data(f) << '\n';
}
示例二:
主线程必须启动10个工作线程,并且在启动所有这些线程之后,主函数将等待它们完成(调用join()
)。加入所有线程后,main函数将继续。
#include <iostream>
#include <thread>
#include <algorithm>
class WorkerThread
{
public:
void operator()()
{
std::cout<<"Worker Thread "<<std::this_thread::get_id()<<" is Executing"<<std::endl;
}
};
int main()
{
std::vector<std::thread> threadList;
for(int i = 0; i < 10; i++)
{
threadList.push_back( std::thread( WorkerThread() ) );
}
// Now wait for all the worker thread to finish i.e.
// Call join() function on each of the std::thread object
std::cout<<"wait for all the worker thread to finish"<<std::endl;
std::for_each(threadList.begin(),threadList.end(),std::mem_fn(&std::thread::join));
std::cout<<"Exiting from Main Thread"<<std::endl;
return 0;
}
参考资料:
- 为什么规定非静态成员函数的左值不可获得
- cppreference :CPP_Value_category VS C_Value_category