基于:How do I expand a tuple into variadic template function's arguments?
#include <string>
#include <iostream>
#include <tuple>
template <typename... Args>
void print_all(const Args &... args) {
((std::cout << " " << args), ...) << std::endl;
}
int main()
{
// Create a tuple
auto values = std::make_tuple(1, 2, 3.4f, 4.5, "bob");
// Need to pass the tuple through the lambda for template type deduction and to pass param to template function?
std::apply([](auto &&... args) { print_all(args...); }, values);
// This does not work - other then there is no parameter I can't see how this does not work
// and how the lambda does work as it has the same (roughly) param list
std::apply(print_all(), values);
return 0;
}
有人可以解释为什么一个有效而另一个无效吗?
最佳答案
在幕后,这个 lambda 表达式 [](auto &&... args) { print_all(args...); }
大致是这样的类型:
struct [unnamed] {
template <typename ...Args>
void operator()(Args&&...args) { ... };
};
它是一种带有模板化operator()
的类型,即重载解析和模板参数推导仅在operator()
被实际调用时发生。另一方面,print_all
是一个模板,因此您无法将其传递给 std::apply
。
换句话说,无论 Args...
是什么,lambda 始终具有相同的类型,但 print_all
不是。您需要先实例化它,然后才能获得指向该函数的指针。正如 Scheff 所说,这很好:
std::apply(&print_all<int, int, float, double, const char*>, values);
关于c++ - 我无法直接将模板函数传递给 std::apply 但我可以通过 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65341873/