1

I am trying to push many function pointer into a vector for later use. However, I run into problems of type problem

/// in the h file
typedef std::function<int(unsigned char *)> func_t;

class A
{
  void init();
  // after some codes declaration
  private:
  B b;
  std::vector<func_t> func_list;

}

class B
{
   int somefunction(unsigned char *);
}

// elsewise in the cpp file of class A
A::init()
{
  func_t f = std:bind(&B::somefunction, &b, std::placeholders::_1);
  func_list.push_back(f);
}

The error seem to occur at the point of std::bind, the error read as

 initializing: cannot convert from 'std::Binder<std::Unforced, void(__thiscall B::*)(unsigned char *), B*, const std::_Ph<1> &>' to std::function<int(unsigned char*)>

The problem goes away if I change the variable f from func_t to auto . Though subsequently I would have the same problem to push into the vector func_list. So I guess my problem is with the type definition or std::bind definition

Thanks

user1538798
  • 1,075
  • 3
  • 17
  • 42

1 Answers1

1

std::bind returns "A function object of unspecified type T, for which std::is_bind_expression::value == true" cppreference

I don't think there is a way to get bind to return func_t (according to convert std::bind to function pointer), but I may be wrong.

Edit: as @Ranoiaetep pointed out, leaving it as func_t without changing to auto, works too.

Changing to auto does work though:

#include <iostream>
#include <functional>
#include <vector>

using namespace std;
typedef std::function<int(unsigned char *)> func_t;

class B
{
public:
int somefunction(unsigned char *);
};

int B::somefunction(unsigned char *) {
    return 1;
};

class A
{
    public:
  void init();
  private:
  B b;
  std::vector<func_t> func_list;

};

void A::init()
{
  auto f = std::bind(&B::somefunction, &b, std::placeholders::_1);
  func_list.push_back(f);
};

int main()
{
    A* a = new A();
    a->init();
    return 0;
}
sleepystar96
  • 721
  • 3
  • 12
  • 2
    You can't convert a bind expression to function pointer. However, an `std::function` can store any *CopyConstructible [Callable](https://en.cppreference.com/w/cpp/named_req/Callable)*, which includes bind expressions. – Ranoiaetep Nov 16 '22 at 02:49