我试图传递一个lambda作为参数

时间:2013-02-14 01:33:23

标签: c++ c++11 lambda std-function

尝试将lambda传递给构造函数:

#include <functional>
#include <exception> 

template<typename R>
class Nisse
{
    private:
        Nisse(Nisse const&)             = delete;
        Nisse(Nisse&&)                  = delete;
        Nisse& operator=(Nisse const&)  = delete;
        Nisse& operator=(Nisse&&)       = delete;
    public:
        Nisse(std::function<R> const& func) {}
};

int main()
{
    Nisse<int>   nisse([](){return 5;});
}

当我编译时,我收到一条错误消息:

Test.cpp: In function ‘int main()’:
Test.cpp:19:39: error: no matching function for call to ‘Nisse<int>::Nisse(main()::<lambda()>)’
Test.cpp:19:39: note: candidate is:
Test.cpp:14:9: note: Nisse<R>::Nisse(const std::function<R>&) [with R = int]
Test.cpp:14:9: note:   no known conversion for argument 1 from ‘main()::<lambda()>’ to ‘const std::function<int>&’

1 个答案:

答案 0 :(得分:5)

std::function模板arg的类型错误。尝试使用

Nisse(std::function<R()> const& func) {}

具体来说,模板参数需要是一个函数类型,但是你传递的只是所需的返回类型。