【发布时间】:2023-03-11 20:05:01
【问题描述】:
最近,我经常将成员函数绑定到对象实例。我不想使用 std::bind、std::mem_fn 和 std::ref 的组合,而是想将所有这些组合成一个函数来自动处理。
例如,考虑以下代码:
#include <functional>
#include <iostream>
#include <string>
// This is the function I'd like to have working:
template <class T, typename RETURN_TYPE, typename... Arguments>
std::function<RETURN_TYPE(Arguments...)> obj_bind(RETURN_TYPE (T::*in_fun)(), T & obj, Arguments... params)
{
return std::bind( std::mem_fn(in_fun), std::ref(obj), params...);
}
int main()
{
// Standard use of push_back member function (our test case):
std::string test_obj = "Test 1: ";
test_obj.push_back('A');
std::cout << test_obj << std::endl;
// This WORKS:
auto test_fun = std::bind( std::mem_fn(&std::string::push_back), std::ref(test_obj), 'B');
// But I'd like to use this instead:
// auto test_fun = obj_bind( &std::string::push_back, test_obj, 'C');
test_obj = "Test 2: ";
test_fun();
std::cout << test_obj << std::endl;
}
我的 obj_bind 函数实际上在没有参数的成员函数上运行良好,所以我很确定我的问题在于我如何处理这些,但是在尝试修复它几次失败后,我想我会在这里尝试建议。
【问题讨论】:
-
Mabye 我遗漏了一些东西,但使用
std::bind你不需要std::mem_fn。 -
我可以确认我刚刚删除了 mem_fn,它在 g++ 上运行良好。也许您正在使用损坏/旧的库?
-
我不明白。
obj_bind与std::bind()有何明显不同?你可以std::bind(&string::push_back, test_obj, 'C'),不是吗? -
啊——我不知何故错过了
std::bind不需要std::mem_fn。这将为我做很多简化。至于与std::bind的区别:std::ref仍然需要绑定到目标对象的引用。 -
std::bind(&string::push_back, &test_obj, 'C')是一个更接近的类比,为此使用&test_obj等效于std::ref(test_obj),它会导致bind引用原始对象而不是复制它
标签: c++ c++11 variadic-templates stdbind