1

I'm trying to use std::bind and typecast the function arguments to use with a typedef function. However, I can't typecast the std::placeholder. Any ideas to implement what I'm trying to do? For varied reasons, I need to be able to have the typedef function have a uint16_t argument, and also have the init function accept a member function that takes a uint8_t argument). The code (edited for simplicity) that I'm using:

typedef void (write_func_t) (uint16_t, uint8_t);

class MyClass {
public:
  MyClass();


  template < typename T >
  void init(void (T::*write_func)(uint8_t, uint8_t), T *instance)     {
    using namespace std::placeholders;
    _write_func = std::bind(write_func, instance, (uint16_t)_1, _2);
    this->init();
  }

private:
  write_func_t *_write_func;

};
Mumblepins
  • 21
  • 1
  • 2
  • 1
    You can't convert a bind expression (`std::bind` result) to a function pointer. Look at `std::function`. – Simple Mar 23 '16 at 16:18

1 Answers1

3

Wouldn't this be cleaner (and much simpler using lambdas and std::function<>)?

class MyClass {
  using WriteFunc = std::function<void(int16_t, int8_t)>;

public:

  void init(WriteFunc&& func) {
    write_func_ = std::move(func);
  }

private:
  WriteFunc write_func_;
};

Then call in some other type..

class Foo {
  // e.g
  void SomeWriteFunction(int8_t x, int8_t y) {
  }

  void bar() {
    // The lambda wraps the real write function and the type conversion
    mc_inst.init([this](int16_t x, int8_t y) {
      this->SomeWriteFunction(x, y);
    });  
  }
};
Nim
  • 33,299
  • 2
  • 62
  • 101