在開發軟件過程中,經常會遇到這樣的需求,設計一個類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