lundi 2 octobre 2023

Is there a way to access arguments stored in the function object returned by std::bind() in C++?

I need a way to decompose the function object returned by std::bind() to its arguments in a function template.

The code snippet below shows what I'd like to do:

#include <iostream>
#include <functional>

void foo(int x, double y, char z)
{
    std::cout << "x = " << x << ", y = " << y << ", z = " << z << '\n';
}

int main()
{
    auto f = std::bind(foo, 42, 3.14, 'a');
    std::cout << "The first argument is: " << std::get<0>(f) << '\n';
    std::cout << "The second argument is: " << std::get<1>(f) << '\n';
    std::cout << "The third argument is: " << std::get<2>(f) << '\n';
}

The output should be:

The first argument is: 42
The second argument is: 3.14
The third argument is: a

But it doesn't compile with the error:

test.cpp:12:60: error: no matching function for call to ‘get<0>(std::_Bind<void (*(int, double, char))(int, double, char)>&)’

Any help would be appreciated.

Aucun commentaire:

Enregistrer un commentaire