从类型的元组到通过调用模板函数返回的值数组

时间:2019-08-23 15:12:28

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

我有一个元组类型定义:

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;

如何为元组类型定义(v)中包含的每种类型编写一个使用模板函数f的返回值填充数组{ f<A>(), f<B>(), f<C>() }的函数? / p>

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

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

1 个答案:

答案 0 :(得分:3)

一种解决方案是编写一个带有参数包的函数模板,该参数包被隐式推导到元组的元素。然后,您可以展开该包并使用以下每种类型调用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{});
}
相关问题