Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using std::apply on class method

I'm trying to get the following to compile (g++-11.2, C++20), but I get:

error: no matching function for call to '__invoke(std::_Mem_fn<void (Foo::*)(int, double)>, std::__tuple_element_t<0, std::tuple<int, double> >, std::__tuple_element_t<1, std::tuple<int, double> >)'
 1843 |       return std::__invoke(std::forward<_Fn>(__f),

Code:

#include <iostream>
#include <tuple>

struct Foo
{
    void bar(const int x, const double y) 
    {  
        std::cout << x << " " << y << std::endl;
    }  


    void bar_apply()
    {  
        // fails
        std::apply(std::mem_fn(&Foo::bar), std::tuple<int, double>(1, 5.0));
    }  
};


int main()
{
    Foo foo;
    foo.bar_apply();
};
like image 791
Agrim Pathak Avatar asked Oct 26 '25 03:10

Agrim Pathak


1 Answers

I recommend using C++20 bind_front, which is more lightweight and intuitive. Just like its name, member functions require a specific class object to invoke, so you need to bind this pointer to Foo::bar.

void bar_apply()
{  
  std::apply(std::bind_front(&Foo::bar, this), std::tuple<int, double>(1, 5.0));
}

Demo.

like image 109
康桓瑋 Avatar answered Oct 28 '25 17:10

康桓瑋



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!