gpt4 book ai didi

c++ - 比较 std::function 与回调 lambda

转载 作者:行者123 更新时间:2023-11-30 05:25:41 25 4
gpt4 key购买 nike

作为线程的继续 Compare of std::function with lambda

我在将 this 捕获到 lambda 时遇到问题 - 然后与“正确的回调”进行比较。

#include <iostream>
#include <functional>
using namespace std;

//////////////////////////////////////////////////////////////////////////
class IFoo
{
public:
virtual void onAppStarted( int, int ) = 0;
};
//////////////////////////////////////////////////////////////////////////
template <typename T>
struct FunctionTypeDeduction;

template<class ClassType, class ReturnType, class... Args>
struct FunctionTypeDeduction< ReturnType( ClassType::* )( Args... ) >
{
using type = ReturnType( *)( Args... );
using functorType = std::function<ReturnType( Args... ) >;
};
//////////////////////////////////////////////////////////////////////////
class SubcribeSystem
{
public:
using tSomeMethodType = FunctionTypeDeduction< decltype( &IFoo::onAppStarted ) >::type;
using tSomeMethodCallback = FunctionTypeDeduction< decltype( &IFoo::onAppStarted ) >::functorType;

public:
void subribeOnSomeMethod( const tSomeMethodCallback& arr )
{
arr( 3, 19 );
}
};
#define SUBCRIBE_FOR_SOMEMETHOD( eventsObj, lambda ) \
do \
{ \
SubcribeSystem::tSomeMethodType const func_ptr = lambda; \
eventsObj.subribeOnSomeMethod( lambda ); \
} \
while(false);
//////////////////////////////////////////////////////////////////////////
class Bar
{
public:
void fn( SubcribeSystem& events )
{
auto onAppStart = []( int width, int height )
{
cout << width << " " << height << endl;
};
auto onAppStart2 = []( bool width, int height )
{
cout << width << " " << height << endl;
};
auto onAppStart3 = [this]( int width, int height )
{
cout << width << " " << height << endl;
someOtherMethod( width );
};
SUBCRIBE_FOR_SOMEMETHOD( events, onAppStart ); // expect all ok
//SUBCRIBE_FOR_SOMEMETHOD( events, onAppStart2 ); // expect error cause bool first param
SUBCRIBE_FOR_SOMEMETHOD( events, onAppStart3 ); // expect all ok, but not !!!
}
void someOtherMethod( int x )
{
cout << "processed callback " << x << endl;
}
};
int main()
{
Bar bar;
SubcribeSystem sub;
bar.fn( sub );
}

最佳答案

在你的宏中你有

SubcribeSystem::tSomeMethodType const func_ptr = lambda; 

SubcribeSystem::tSomeMethodType 是一个

FunctionTypeDeduction< decltype( &IFoo::onAppStarted ) >::type

这是一个函数指针。所以你试图将 lambda 转换为函数指针。不幸的是,onAppStart3 捕获的 lambda 无法转换为函数指针。

前两个 lambda 的工作原理是它们不捕获,因此它们具有隐式函数指针转换运算符。

关于c++ - 比较 std::function 与回调 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38147559/

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