7
#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)

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
Xuan Lin
  • 81
  • 3
  • 3
    What is the error you get? – new Q Open Wid Aug 22 '22 at 16:03
  • 3
    If you'd use a new fangled *lambda* instead of an old fashioned *bind*, you could have do_task `[&]{ func(forward(args)...); }();` – Eljay Aug 22 '22 at 16:11
  • 3
    TL:DR of the dupes: the bound function can be called multiple times. Because of that `bind` 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 from `bind` invalid. – NathanOliver Aug 22 '22 at 16:22

0 Answers0