c++ - 类型转换 std::placeholder

标签 c++ c++11 casting stdbind

我正在尝试使用 std::bind 并对函数参数进行类型转换以与 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;

};

最佳答案

这不是更干净(并且使用 lambda 和 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);
    });  
  }
};

关于c++ - 类型转换 std::placeholder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36182824/

相关文章:

c++ - C++中关键字new的解释

c++ - 函数内的静态 constexpr 变量是否有意义?

c++ - 在两个 vector 中对 vector 进行空间高效解包的优雅方法

c++ - 动态类型转换的局限性是什么?

ios - Swift,如果让..作为?一些字符串

c++ - 自制字符串类中的异常

c++ - 在 Qt TableView 中更改数据

c++ - 创建返回 std::pair 的 C++ 容器的迭代器

c++ - 编译错误: invalid conversion when calling base-type constructor

php - 如何在 PHP 中将字符串转换为数字?