c++ - 传递成员函数时替代 std::bind
问题描述
我有一些我想进行基准测试的功能。我希望能够将它们传递给基准测试功能。以前我已经将函数指针和对对象的引用传递给测试函数,就像这样
template<typename T>
void (T::*test_fn)(int, int), T& class_obj, )
目前我有这个
#include <iostream>
#include <functional>
using namespace std::placeholders;
class aClass
{
public:
void test(int a, int b)
{
std::cout << "aClass fn : " << a + b << "\n";
}
};
class bClass
{
public:
void test(int a, int b)
{
std::cout << "bClass fn : " << a * b << "\n";
}
};
// Here I want to perform some tests on the member function
// passed in
class testing
{
public:
template<typename T>
void test_me(T&& fn, int one, int two)
{
fn(one, two);
}
};
int main()
{
aClass a;
bClass b;
auto fn_test1 = std::bind(&aClass::test, a, _1, _2);
auto fn_test2 = std::bind(&bClass::test, b, _1, _2);
testing test;
test.test_me(fn_test1, 1, 2);
test.test_me(fn_test2, 1, 2);
}
有没有办法我可以使用 lambda 来代替?我知道我可以使用 std::bind 来做到这一点,但我可以使用 lambda 来做到这一点,而不必每次都为我想测试的每个成员函数都这样做(如下所示)?
解决方案
该test_me
函数可以采用任何可调用对象。包括 lambda。无需修改。
就像是
test.test_me([a](int one, int two) { a.test(one, two); }, 1, 2);
推荐阅读
- php - 将 Crypto-js 预请求脚本转换为 PHP
- python - 如何使用 python 获取印度格式的货币?
- javascript - 如何在一端制作svg曲线
- azure - 如何为 azure timer trigger 功能配置高可用性?
- excel - VBA 格式化以基于复选框突出显示文本
- simulation - AFU 模拟环境(ASE 环境)设置问题;无法将 / 复制到 /target-directory Traceback(最近的调用):
- numpy - torch.where() 可以以等效的广播形式使用吗?
- php - 无法使用 php 或 nodejs 读取串口
- python - Assign class label based on parent folder name when using Tf.data
- reactjs - 使用 Flask Socket Io 和 Reactjs 进行连续数据传输