C++ 为什么std::stol不能转换为std::function对象? #包括 #包括 使用名称空间std; int main() { 函数fn=stol; }

C++ 为什么std::stol不能转换为std::function对象? #包括 #包括 使用名称空间std; int main() { 函数fn=stol; },c++,function,c++11,constructor,type-conversion,C++,Function,C++11,Constructor,Type Conversion,无法按预期编译上述代码,错误如下: 错误:“std::function”(又名“function”)的初始化没有匹配的构造函数 原因有二: std::stol的第二个参数的类型是std::size\u t*,而不是std::size\u t std::stol被重载,以同时接受const std::wstring&作为其第一个参数 你必须写: #include <functional> #include <string> using namespace std; in

无法按预期编译上述代码,错误如下:

错误:“std::function”(又名“function”)的初始化没有匹配的构造函数

原因有二:

  • std::stol
    的第二个参数的类型是
    std::size\u t*
    ,而不是
    std::size\u t
  • std::stol
    被重载,以同时接受
    const std::wstring&
    作为其第一个参数
  • 你必须写:

    #include <functional>
    #include <string>
    
    using namespace std;
    
    int main()
    {
        function<long(const string&, size_t, int)> fn = stol;
    }
    
    功能fn=
    静态铸造(stol);
    

    附录(2019年7月):在C++20中,上述解决方案无效(见注释)。您必须改用lambda。

    首先,它应该会有所帮助。请注意参数,并将其与您的参数进行比较。
    std::stol()
    的第二个参数是
    size\u t*
    指针,而不是像您这样的
    size\u t
    值。如果您将其编写为:
    typedef long sig(const std::string&,size\u t*,int),重复性会稍小一些;const auto pstoll=静态强制转换(std::stol);常数std::函数fn=pstoll-但它仍然很糟糕。哦,我想:
    typedef long sig(const std::string&,size\u t*,int);const std::function fn=静态_cast(std::stol)
    也有效。@L.F.似乎在C++20中添加了新的措辞,所以在编写时这个答案是正确的。我将添加一个关于它如何在C++20中中断的注释。
    function<long(const string&, size_t*, int)> fn =
      static_cast<long(*)(const string&, size_t*, int)>(stol);