[英]How to have lambda as member function's parameter of the template class
I have C++ class which is template.我有 C++ 类,它是模板。 it have member function which should take any lamda as parameter;
它有成员函数,应该将任何 lamda 作为参数;
basically this is what I wanna do:-基本上这就是我想做的:-
#include <QFuture>
#include <QFutureWatcher>
template <class T>
class EFuture {
private:
QFuture<T> future;
QFutureWatcher<T> watcher;
public:
explicit EFuture(QFuture<T> &future);
void onFinished(void (*f)() );
};
template <class T>
EFuture<T>::EFuture(QFuture<T> &future ): future(future)
{ }
template<class T>
void EFuture<T>::onFinished(void (*f)()){
QObject::connect(watcher,&QFutureWatcher<T>::finished,f);
watcher.setFuture(future);
}
This have serious restriction as I can't capture anything in lambda which I am passing.这有严重的限制,因为我无法在我通过的 lambda 中捕获任何内容。 where I try to do something like this:-
我尝试做这样的事情: -
future->onFinished([someobject](){
...
});
I get following error:-我收到以下错误:-
connectionworker.cpp:106:24: error: no viable conversion from '(lambda at /home/noone/Development/Exatation/Exever/src/connectionworker.cpp:106:24)' to 'void (*)()'
efuture.h:17:28: note: passing argument to parameter 'f' here
Only non-capturing and non-generic lambda expressions are convertible to a function pointer.只有非捕获和非泛型 lambda 表达式才能转换为函数指针。 Itself, any lambda expression -- both captureless and capturing ones -- has its own type, known only to the compiler.
任何 lambda 表达式——无论是无捕获的还是捕获的——都有自己的类型,只有编译器知道。 In such a case, there are two alternatives:
在这种情况下,有两种选择:
Use a function template that can deduce the type of the lambda expression:使用可以推断 lambda 表达式类型的函数模板:
template <typename F> void onFinished(F f);
Use a type-erasing technique, eg, std::function<void()>
:使用类型擦除技术,例如
std::function<void()>
:
#include <functional> void onFinished(std::function<void()> f);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.