在类方法上使用 std::apply

Agr*_*hak 3 c++ tuples c++17 c++20 stdapply

我试图编译以下内容(g++-11.2,C++20),但我得到:

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),
Run Code Online (Sandbox Code Playgroud)

代码:

#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();
};
Run Code Online (Sandbox Code Playgroud)

康桓瑋*_*康桓瑋 7

我推荐使用 C++20 bind_front,它更轻量且直观。正如它的名字一样,成员函数需要特定的类对象来调用,因此您需要将指针绑定 到.thisFoo::bar

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

演示。