#include <functional>
#include <iostream>
#include <string>
#include <utility>
using namespace std;
template<typename Func, typename... Args>
void do_task(Func &func, Args &&...args)
{
auto f = bind(func, forward<Args>(args)...);
f();
}
int main()
{
string name = "hello";
auto test_func = [](string name, string &&arg1, string &&arg2) -> void {
cout << name << " " << arg1 << " " << arg2 << endl;
};
// do_task(test_func,"test_one", "hello", string("world")); // compile error
// do_task(test_func, "test_tww", std::move(name), "world"); // compile error
do_task(test_func, "test_three", "hello", "world"); // compile ok
return 0;
}
In my understanding, string("word")
and std::move(name)
both have the right value, but test_one and test_tww can't compile. (g++ (GCC) 12.1.1 20220730)
[&]{ func(forward<Args>(args)...); }();
– Ushaushantbind
always passes the stored value as an lvalue. if it was an rvalue it could be moved from making any subsequent calls to the functor returned frombind
invalid. – Dung