【问题标题】:Why cannot std::stol be converted to a std::function object?为什么不能将 std::stol 转换为 std::function 对象?
【发布时间】:2017-04-22 01:56:50
【问题描述】:
#include <functional>
#include <string>

using namespace std;

int main()
{
    function<long(const string&, size_t, int)> fn = stol;
}

上面的代码无法按预期编译,出现以下错误:

错误:没有用于初始化 'std::function' 的匹配构造函数(又名 'function, 分配器 > &, unsigned long long, int)>')

【问题讨论】:

  • 首先,this std::stol reference 应该会有所帮助。记下这些论点,并将它们与你的比较。
  • std::stol() 的第二个参数是一个size_t* 指针,而不是像你这样的size_t 值。

标签: c++ function c++11 constructor type-conversion


【解决方案1】:

两个原因:

  1. std::stol 的第二个参数的类型为 std::size_t*,而不是 std::size_t
  2. std::stol 被重载以接受 const std::wstring&amp; 作为其第一个参数。

你必须写:

function<long(const string&, size_t*, int)> fn =
  static_cast<long(*)(const string&, size_t*, int)>(stol);

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

【讨论】:

  • 如果你把它写成:typedef long sig(const std::string&amp;, size_t*, int); const auto pstoll = static_cast&lt;sig*&gt;(std::stol); const std::function&lt;sig&gt; fn = pstoll;,那么重复稍微少 - 但它仍然很讨厌。
  • 哦,我想:typedef long sig(const std::string&amp;, size_t*, int); const std::function&lt;sig&gt; fn = static_cast&lt;sig*&gt;(std::stol); 也可以。
  • @L.F.似乎在 C++20 中添加了新的措辞,所以这个答案在编写时是正确的。我将添加一条关于它如何在 C++20 中中断的注释。
猜你喜欢
  • 2014-03-02
  • 1970-01-01
  • 1970-01-01
  • 2012-06-25
  • 2014-12-11
  • 2018-11-06
  • 2017-07-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多