本文介绍了如何访问QObject :: sender在C ++ lambda?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个相当不寻常的问题 - 但仍然是一个问题。我有一个函数接受一个lambda作为参数,然后将其传递给 QObject :: connect

  template< typename Functor> 
void MyClass :: doSomething(Functor f)
{
connect(network_reply,& QNetworkReply :: finished,f);
// ...
}

调用 MyClass :: doSomething 可能如下所示:

  doSomething b $ b {
//如何访问发件人?
});

正如你可以通过我的评论所知,没有办法访问 QObject :: sender 以获取发出信号的 QObject 的指针。因为发出信号的类不在创建lambda的范围内,所以无法在lambda中引用它。



我有什么选项?

我尝试使用Andy的建议( std:<$> :bind ),但我最终得到几乎不可能理解的模板错误之一:





摘录:

/ p>

 decltype无法解析重载函数的地址

... QObject :: connect 调用。

解决方案

,你可以首先让你的lambda函数接受一个适当类型的参数(通过引用这里,所以照顾生命周期问题):

  doSomething([](QNetworkReply * p)
{
//这里你的发件人由p
}引用);

然后,您的 doSomething()模板函数可以使用 std :: bind()来确保将使用适当的对象作为其参数来调用您的lambda:

  template< typename Functor> 
void MyClass :: doSomething(Functor f)
{
connect(network_reply,& QNetworkReply :: finished,bind(f,network_reply));
// ...
}


This is a rather unusual problem - but a problem nonetheless. I have a function that accepts a lambda as a parameter and then passes it on to QObject::connect:

template<typename Functor>
void MyClass::doSomething(Functor f)
{
    connect(network_reply, &QNetworkReply::finished, f);
    //...
}

A sample invocation of MyClass::doSomething might look like this:

doSomething([]()
{
    // how do I get access to the sender???
});

As you can tell by my comment, there is no way to access QObject::sender to get a pointer to the QObject that emitted the signal. Because the class emitting the signal is not in the scope that the lambda is being created in, there is no way of referencing it inside the lambda.

What options do I have?


Edit: I tried using Andy's suggestion (std::bind) but I end up getting one of those template errors that are nearly impossible to understand:

http://paste.ubuntu.com/1614425/

Excerpt:

decltype cannot resolve address of overloaded function

...and it points to the QObject::connect call.

解决方案

If I understood your requirements correctly, you can first let your lambda functor accept an argument of the appropriate type (passing by reference here, so take care of lifetime issues):

doSomething([](QNetworkReply* p)
{
    // Here you have the sender referenced by p
});

Then, your doSomething() template function could use std::bind() to make sure your lambda will be invoked with the appropriate object as its argument:

template<typename Functor>
void MyClass::doSomething(Functor f)
{
    connect(network_reply, &QNetworkReply::finished, bind(f, network_reply));
    //...
}

这篇关于如何访问QObject :: sender在C ++ lambda?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 18:16