输入cast std :: placeholder

时间:2016-03-23 15:52:08

标签: c++ c++11 casting stdbind

我正在尝试使用std :: bind和typecast函数参数来与typedef函数一起使用。但是,我不能对std :: placeholder进行类型转换。有任何想法来实现我想要做的事情吗?由于各种原因,我需要能够让typedef函数有一个uint16_t参数,并且还有init函数接受一个带有uint8_t参数的成员函数。我正在使用的代码(为简单而编辑):

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;

};

1 个答案:

答案 0 :(得分:3)

这不是更清洁(使用lambdas和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_;
};

然后打电话给其他类型..

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);
    });  
  }
};