一、std::funtion
template.h
#pragma once
#include <iostream>
#include <map>
#include <functional>
class RC
{
public:
void operator()(int tv)
{
std::cout << "RC operator:" << tv << std::endl;
}
};
void myrcFun(int tv)
{
std::cout << "myrcFun:" << tv << std::endl;
}
class RC2
{
public:
using tfpoint = void(*)(int);
static void myfunc(int tv)
{
std::cout << "RC2 static myfunc:" << tv << std::endl;
}
operator tfpoint() { return myfunc; }
};
main.cpp
#include <iostream>
#include "template.h"
using namespace std;
int main()
{
std::function<void(int)> f1 = myrcFun;
f1(100);
std::function<void(int)> f2 = RC2::myfunc;
f2(200);
RC rc;
std::function<void(int)> f3 = rc;//可调用对象,调用了operator()
f3(300);
RC2 rc2;
std::function<void(int)> f4 = rc2;//可调用对象,类型转换运算符,operator tfpoint() { return myfunc; }转为为指针
f4(300);
}
为什么叫可调用对象呢?
RC rc;
rc(4);
实际上是调用RC类的operator(),但看上去像用对象直接调用了函数,所以叫做可调用对象。
二、std::bind
template.h
#pragma once
#include <iostream>
#include <map>
#include <functional>
void myfun1(int x, int y, int z)
{
std::cout << "x:" << x << ",y:" << y << ",z:" << z << std::endl;
}
void myfun2(int &x, int& y)
{
x++;
y++;
}
class QT
{
public:
void myfunc(int x, int y)
{
std::cout << "x:" << x << ",y:" << y << std::endl;
m_a = x;
}
int m_a = 0;
};
class RC
{
public:
void operator()(int tv)
{
std::cout << "RC operator:" << tv << std::endl;
}
};
main.cpp
#include <iostream>
#include "template.h"
using namespace std;
int main()
{
//绑定函数
auto bf2 = std::bind(myfun1, placeholders::_1, placeholders::_2, 100);
bf2(3, 4);
int test1 = 2;
int test2 = 3;
auto bf4 = std::bind(myfun2, test1, placeholders::_1);
bf4(test2);
cout << "test1:" << test1 << "test2:" << test2 << endl;//输出为2和4,因为提前绑定了test1,所以是值传递
//绑定成员函数
QT qt;
auto qtfunction = std::bind(&QT::myfunc, &qt, placeholders::_1, placeholders::_2);//注意这里已经要传递引用,不然会调用拷贝构造函数,生成新qt对象。myfunc修改的成员变量不是针对原qt对象,而是新qt对象。原qt对象的成员变量不会被改变
qtfunction(10, 20);
//绑定成员变量
std::function<void(int, int)> qtfunc1 = std::bind(&QT::myfunc, &qt, placeholders::_1, placeholders::_2);
std::function<int &(void)> qtVar = std::bind(&QT::m_a, &qt);
qtVar() = 40;
//绑定可调用对象
auto rcfun1 = std::bind(RC(), 2);
rcfun1();
}
std::bind除了类似std::funtion可以绑定函数外,还可以指定参数。
输出:
x:3,y:4,z:100
test1:2,test2:4
x:10,y:20
RC operator:2
本文深入探讨了C++中std::function和std::bind的使用,解释了可调用对象的概念,并展示了如何利用std::bind绑定函数、成员函数及成员变量,实现灵活的函数调用。
1万+

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



