3
votes
#include <functional>
#include <string>

using namespace std;

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

The code above cannot be compiled as expected with the following error:

error : no matching constructor for initialization of 'std::function<long (const std::string &, std::size_t, int)>' (aka 'function<long (const basic_string<char, char_traits<char>, allocator<char> > &, unsigned long long, int)>')

1
To begin with, this std::stol reference should be helpful. Note the arguments, and compare them with yours.Some programmer dude
The second parameter of std::stol() is a size_t* pointer, not a size_t value like you have it.Remy Lebeau

1 Answers

8
votes

Two reasons:

  1. The second argument of std::stol has type std::size_t*, not std::size_t.
  2. std::stol is overloaded to also accept const std::wstring& as its first argument.

You would have to write:

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

Addendum (July, 2019): In C++20, the solution described above becomes invalid (see comments). You have to use a lambda instead.