c++ - 我无法直接将模板函数传递给 std::apply 但我可以通过 lambda

标签 c++ templates tuples

基于: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/

相关文章:

c++ - 在 Boost Graph Library 中将自定义属性添加到网格的顶点

c++ - glibc 检测 smallbin 链表损坏

C++ std::plus 作为模板参数

python - 遍历元组内的元组并使用元组内的字符串作为变量

c++ - 关于最令人烦恼的解析的一个令人困惑的细节

c++ - 在C++中交换短语中单词的前两个字母

java - Velocity #foreach 与 XmlTool 节点列表与文本节点

c++ - 为什么模板类型推导在这里失败了?

python - 创建元组,其中第一个元素是混合大小写的单词,第二个元素是完全小写的字符串

python - 为什么Python的元组没有任何方法?