std::invoke不像可变的模板成员函数?



我正在尝试使用std::invoke()std::apply()调用可变函数模板。

我提前道歉,因为我基本上是在这里丢了一小段代码,并请某人帮助我理解错误信息以解决问题。

那么,在下面的示例代码中,

  • std::invoke()上的非可变模板函数工作正常
  • std::invoke()上的可变模板函数不编译!
#include <functional>
#include <tuple>
struct Thing
{
// Some simple functions to test things out
int func0() { return 0; }
int func1(int) { return 1; }
int func2(int, int) { return 2; }
// A variadic template function that causes problems below
template<typename ...Args>
int funcn(Args&&...) { return 99; }
};
int main()
{
Thing thing;
// These work fine
std::invoke(&Thing::func0, thing);
std::invoke(&Thing::func1, thing, 1);
std::invoke(&Thing::func2, thing, 1, 2);
// This one doesn't work
std::invoke(
&Thing::funcn, 
thing, 
1, 2, 3, 4
);
}

我得到的错误是在这里:(输出x86-64 clang 12.0.1(编译器#1))

Wrap lines
<source>:26:5: error: no matching function for call to 'invoke'
std::invoke(
^~~~~~~~~~~
functional:94:5: note: candidate template ignored: couldn't infer template argument '_Callable'
invoke(_Callable&& __fn, _Args&&... __args)
^

std::invoke期望一个可调用的函数。funcn是一个函数模板,您需要实例化以从中获得一个真正的函数,然后您可以获取它的地址。

这意味着(显式地)为函数提供模板参数,您希望如何实例化它,以便std::invoke可以看到它可以调用的函数。

std::invoke(
&Thing::funcn<int, int, int, int>, // works now
thing,
1, 2, 3, 4
);

最新更新