【发布时间】:2021-11-18 01:14:00
【问题描述】:
我正在尝试使用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)
^
【问题讨论】:
-
&Thing::funcn尝试获取函数的地址,但由于它是一个模板,它没有可以解析到的单个地址。您要么需要指定参数,将其转换为正确的类型,要么将其包装在 lambda 中。
标签: c++ templates c++17 variadic-templates std-invoke