why I can't bind function with rvalue args like this? [duplicate]
Asked Answered
P

0

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)

Pernambuco answered 22/8, 2022 at 16:1 Comment(3)
What is the error you get?Thiazole
If you'd use a new fangled lambda instead of an old fashioned bind, you could have do_task [&]{ func(forward<Args>(args)...); }();Ushaushant
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.Dung

© 2022 - 2025 — McMap. All rights reserved.