Xua*_*Lin 7 c++ templates rvalue-reference stdbind stdmove
#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;
}
Run Code Online (Sandbox Code Playgroud)
根据我的理解,string("word")
两者std::move(name)
都有正确的值,但 test_one 和 test_tww 无法编译。(g++(海湾合作委员会)12.1.1 20220730)