1

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

1 回答 1

5

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

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

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

于 2013-02-14T01:37:04.950 回答