非成员函数
非成员函数可以用指针直接调用
#include <iostream>
#include <string>
#include <functional>
using namespace std;
void NonMemFunc()
{
std::cout << __func__ << "()" << std::endl;
}
int main()
{
void (*f)() = NonMemFunc;
f();
return 0;
}
// 输出:NonMemFunc()
成员函数
成员函数(静态函数除外)是无法直接用指针调用,函数调用必须有对应的对象通过class_obj.*func()或class_obj->*func()
#include <iostream>
#include <string>
#include <functional>
using namespace std;
class test
{
public:
test() {}
void print(const std::string &str)
{
std::cout << __func__ << "() " << str << std::endl;
}
~test() {}
};
int main(int argc, char **argv)
{
test t;
auto func = &test::print;
(t.*func)("ffff");
return 0;
}
// 输出:print() ffff
由此可以看出,两种函数的调用方式不同,故std::bind在实现时是会对是否为成员函数作区分的。而标准库正好提供了这一个函数std::is_member_function_pointer<decltype(NonMemFunc)>::value,value为true则表示函数为成员函数,为false表示为非成员函数。
如下图是bind函数的实现
_Bind_helper有个数据类型为type,其就是一个执行接口,由其内部在进行区分。



圈出来的这三种分别是非成员函数,有参成员函数,有参成员函数

具体的实现可以参考 https://zhuanlan.zhihu.com/p/143764465
本文探讨了非成员函数与成员函数(静态成员除外)在调用上的区别,指出非成员函数可以直接用指针调用,而成员函数需要对象来调用。通过示例代码展示了这两种函数的调用语法。同时,提到了`std::bind`在实现时会根据函数类型进行区分,并利用`std::is_member_function_pointer`来判断函数是否为成员函数。文章还介绍了`_Bind_helper`的数据类型`type`作为执行接口,用于区分不同类型的函数。
774

被折叠的 条评论
为什么被折叠?



