尝试将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>&’

最佳答案

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

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

具体来说,模板参数必须是函数类型,但您传递的只是所需的返回类型。

09-06 14:54