使用std::bind分别绑定参数和对象实例
Using std::bind to bind parameters and object instance separately
是否可以将参数绑定到成员函数调用,然后单独绑定目标对象?
我试图实现的是一个助手函数,它接收一个带有任意参数的函数作为参数,然后在集合中的所有项上执行它。
void SomeType::Work(UINT a, UINT b, UINT c)
{
//do something
}
template<typename Function, class Container>
void Execute(const Function& fn, const Container& collection)
{
for(auto& item : collection)
{
auto bound = std::bind(fn, &item);
bound();
}
}
void Test()
{
//eg. container = vector of SomeType
auto fn = std::bind(&Sometype::Work, 10, 20, 30);
Execute(fn, container);
}
这是由于功能中的一些错误而失败的:
error C2064: term does not evaluate to a function taking 3 arguments
最终指向:
see reference to function template instantiation 'void Execute<std::_Bind<true,void,std::_Pmf_wrap<void (__thiscall SomeType::* )(UINT,UINT,UINT),void,SomeType,UINT,UINT,UINT>,UINT &,UINT &,UINT &>>(const Function &)' being compiled
with
[
Function=std::_Bind<true,void,std::_Pmf_wrap<void (__thiscall SomeType::* )(UINT,UINT,UINT),void,SomeType,UINT,UINT,UINT>,UINT &,UINT &,UINT &>
]
我只是通过传递一个lambda来解决这个问题,该lambda捕获所需的值,并在传递到它的对象上执行所需的函数。我仍然在想,以这种方式绑定函数是否有任何问题,我只是做错了,或者这是不可行的。
当绑定成员函数Sometype::Work()
时,您应该为目标对象保留一个占位符,该占位符将在第二次绑定时绑定。
试试这个:
using namespace std::placeholders;
auto fn = std::bind(&Sometype::Work, _1, 10, 20, 30);
~~
实时
听起来您只是想将一个函数(带有特定参数(应用于集合。
我看不出这与使用具有特定函数的std::for_each
有什么不同。
void Test()
{
//eg. container = vector of SomeType
auto fn1 = [/*whatever*/](const container_value_type& obj) {
Sometype::Work(10, 20, 30, obj);
}
auto fn2 = [/*whatever*/](const container_value_type& obj) {
Sometype::Work(40, 50, 60, obj);
}
std::for_each(container.begin(), container.end(), fn1);
std::for_each(container.begin(), container.end(), fn2);
}
相关文章:
- 如何使用Visual Studio 2017在C++中为参数化对象数组使用唯一指针
- Arduino C++在构造函数中用参数声明对象数组
- 我使用向量来创建类对象列表.初始化向量时如何使用参数调用构造函数?
- 当指向对象的指针作为参数传递给 std::thread 时,内存可见性
- 如何在不使用指针的情况下将派生类的对象作为参数传递给基类中的函数?
- C++ 类对象作为函数参数
- 如何将对象数组作为参数传递给模板
- 使用向量初始化参数化构造函数的对象数组
- 如何将成员函数作为参数传递并在派生对象上执行方法列表
- 如何编写将展开以定义具有模板参数的对象的宏
- C++类对象 - 遍历基于参数的对象
- 将指针传递到成员的指针,从模板参数包到函数对象
- 如何将子类作为函数的参数传递给期望基类,然后将该对象传递到指向这些抽象类对象的指针向量中?
- 是否可以获取成员函数模板参数的拥有对象?
- C++多参数对象创建
- 在不创建参数对象的情况下解析constexpr函数
- 推断模板参数对象成员的类型
- 如何解析c++ v8中的参数对象
- 当默认参数对象被销毁时
- 为什么函数不能更改其参数对象的地址/引用值?