【问题标题】:How to have lambda as member function's parameter of the template class如何将lambda作为模板类的成员函数参数
【发布时间】:2020-06-06 04:07:37
【问题描述】:

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

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

#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

【问题讨论】:

  • 改用void onFinished(std::function&lt;void()&gt; f);
  • @PiotrSkotnicki 谢谢。它奏效了

标签: c++ c++11 templates lambda


【解决方案1】:

只有非捕获和非泛型 lambda 表达式可以转换为函数指针。任何 lambda 表达式本身——无论是无捕获的还是捕获的——都有自己的类型,只有编译器知道。在这种情况下,有两种选择:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2021-09-04
    • 2011-07-06
    • 1970-01-01
    • 2013-11-06
    • 2016-06-25
    • 1970-01-01
    相关资源
    最近更新 更多