C++ 类型转换std::占位符
我正在尝试使用std::bind和typecast函数参数与typedef函数一起使用。但是,我无法键入std::占位符。有什么想法可以实现我想做的吗?出于各种原因,我需要使typedef函数具有uint16_t参数,并且使init函数接受接受uint8_t参数的成员函数)。我正在使用的代码(为简单起见进行了编辑):C++ 类型转换std::占位符,c++,c++11,casting,stdbind,C++,C++11,Casting,Stdbind,我正在尝试使用std::bind和typecast函数参数与typedef函数一起使用。但是,我无法键入std::占位符。有什么想法可以实现我想做的吗?出于各种原因,我需要使typedef函数具有uint16_t参数,并且使init函数接受接受uint8_t参数的成员函数)。我正在使用的代码(为简单起见进行了编辑): typedef void (write_func_t) (uint16_t, uint8_t); class MyClass { public: MyClass();
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;
};
typedef void(写入函数)(uint16、uint8);
类MyClass{
公众:
MyClass();
模板
void init(void(T::*write_func)(uint8_T,uint8_T),T*实例){
使用名称空间std::占位符;
_write_func=std::bind(write_func,实例,(uint16_t)_1,_2);
这个->初始化();
}
私人:
write_func_t*_write_func;
};
这不是更干净(使用lambdas和std::function
)更简单吗
无法将绑定表达式(
std::bind
result)转换为函数指针。查看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);
});
}
};