如何将lambda作为模板类的成员函数参数

How to have lambda as member function's parameter of the template class

本文关键字:成员 函数 参数 lambda      更新时间:2023-10-16

我有C++类,它是模板。它具有成员函数,该函数应以任意λ为参数;

基本上这就是我想做的:-

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

这有严重的限制,因为我无法在lambda中捕获我正在经过的任何内容。我尝试做这样的事情:-

future->onFinished([someobject](){
...
});

我得到以下错误:-

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

只有非捕获和非泛型lambda表达式才能转换为函数指针。就其本身而言,任何lambda表达式——包括无捕获表达式和捕获表达式——都有自己的类型,只有编译器知道。在这种情况下,有两种选择:

  • 使用一个可以推断lambda表达式类型的函数模板:

    template <typename F>
    void onFinished(F f);
    
  • 使用类型擦除技术,例如std::function<void()>:

    #include <functional>
    void onFinished(std::function<void()> f);