我正在尝试使用 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/