在开发软件过程中,经常会遇到这样的需求,设计一个类Call来进行通用的逻辑处理,但是需要调用另外一个类A,或B中一些函数,这时就不能直接传送类A或类B的指针进来了,如果在以往一般采用静态函数,或者类A和类B是继承关系采用多态来实现。目前可以采用std::function来实现函数对象的调用,也可以实现多态的方式。如下面的例子:
// ConsoleBind.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <functional>
using Callback_t = std::function<void(int, int)>;
class Call
{
public:
void print(Callback_t fun)
{
fun(1, 2);
}
};
class A
{
public:
void print(int x, int y)
{
std::cout << "A:" << x << "," << y << std::endl;
}
void run(void) {
Callback_t fun = std::bind(&A::print, this, std::placeholders::_1, std::placeholders::_2);
m_call.print(fun);
}
Call m_call;
};
class B
{
public:
void print(int x, int y)
{
std::cout << "B:" << x << "," << y << std::endl;
}
void run(void) {
Callback_t fun = std::bind(&B::print, this, std::placeholders::_1, std::placeholders::_2);
m_call.print(fun);
}
Call m_call;
};
int main()
{
std::cout << "Hello World!\n";
A a;
B b;
a.run();
b.run();
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
在这个例子里,使用using来定义一个函数对象声明类型,然后用std::bind动态地构造一个函数对象,这个对象就可以传递给调用类了。就可以实现组合方式调用的多态功能。
输出如下:
Hello World!
A:1,2
B:1,2