【问题标题】:From a tuple of types to an array of values returned by calling a template function从类型元组到调用模板函数返回的值数组
【发布时间】:2019-08-23 15:12:28
【问题描述】:

我有一个元组类型定义:

using types = std::tuple<A,B,C>;

我有一个模板函数:

template <typename T>
uint32 f() { return 0; }

我定义了以下类型和变量(一个数组,其元素类型是函数的返回类型,大小是元组中的类型数):

using result_values = std::array<uint32, std::tuple_size<types>::value>;
result_values v;

对于元组类型定义 ({ f&lt;A&gt;(), f&lt;B&gt;(), f&lt;C&gt;() }) 中包含的每种类型,我如何编写一个函数,用模板函数 f 的返回值填充数组 v

当然,元组类型是未知的,并且作为模板参数出现在某个地方。

我的猜测使我找到了一个使用index_sequence_fortuple_element 和递归调用的解决方案,但我无法将它们放在一起。

【问题讨论】:

  • 你不能只使用{ f&lt;types&gt;(), ... } 吗?
  • 编译器告诉我扩展模式不包含参数包(元组类型不是参数包)。

标签: c++ templates tuples template-meta-programming


【解决方案1】:

一种解决方案是编写一个带有参数包的函数模板,该参数包隐含地推导出到元组的元素中。然后您可以展开该包并使用每种类型调用f

template<class ... T>
std::array<uint32_t, sizeof...(T)> 
foo(const std::tuple<T...> &)
{
    return{ f<T>()... };
}

完整示例:

#include <array>
#include <cstdint>
#include <tuple>

struct A {};
struct B {};
struct C {};

template<class T>
uint32_t f() { return 0; }

using types = std::tuple<A, B, C>;

template<class ... T>
std::array<uint32_t, sizeof...(T)> 
foo(const std::tuple<T...> &)
{
    return{ f<T>()... };
}

int main()
{
    auto result = foo(types{});
}

【讨论】:

  • 这就是我想的那个。 OP - 您需要在包上创建一个模板化的上下文,以使用包扩展。您不能只在顶级非模板代码中执行此操作。
  • 谢谢你们。实例化元组是关键,解决方案比我预期的要简单得多!
猜你喜欢
  • 2023-02-02
  • 1970-01-01
  • 2011-02-14
  • 1970-01-01
  • 2012-06-21
  • 1970-01-01
  • 1970-01-01
  • 2023-02-05
  • 1970-01-01
相关资源
最近更新 更多