gpt4 book ai didi

c++ - 传递成员函数时替代 std::bind

转载 作者:太空狗 更新时间:2023-10-29 20:33:32 24 4
gpt4 key购买 nike

我有一些函数想要进行基准测试。我希望能够将它们传递给基准测试功能。以前我已经像这样将一个函数指针和对对象的引用传递给测试函数

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);

关于c++ - 传递成员函数时替代 std::bind,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54479634/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com