c ++ 11:从模板函数构建std :: tuple [英] c++11: building a std::tuple from a template function

查看:379
本文介绍了c ++ 11:从模板函数构建std :: tuple的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下功能:

template<class T>
T Check(int index);

如何写一个函数 CheckTuple ,在给定一个元组类型的情况下,使用对检查 c>

How can I write a function, CheckTuple, which, given a tuple type, populates a tuple with calls to Check?

例如:

CheckTuple< std::tuple<int, float, std::string> >()

将返回以下元组:

std::make_tuple( Check<int>(1), Check<float>(2), Check<std::string>(3) )

我看到的其他问题涉及解包给定的元组,而不是以这种方式构建。

The other questions I see involve unpacking a given tuple, not building one up this way.

推荐答案

使用C ++ 14的 integer_sequence 。如果您没有可用的资源,请这是一个C ++ 11实现 Jonathan Wakely 撰写。

Implementing what you're looking for becomes pretty simple using C++14's integer_sequence. If you don't have that available, here's a C++11 implementation written by Jonathan Wakely.

template<typename Tuple, int... I>
Tuple CallCheck(std::integer_sequence<int, I...>)
{
    return std::make_tuple(Check<typename std::tuple_element<I, Tuple>::type>(I)...);
}

template<typename Tuple>
Tuple CheckTuple()
{
    return CallCheck<Tuple>(std::make_integer_sequence<int, std::tuple_size<Tuple>::value>());
}

// Use it as 
auto tup = CheckTuple<std::tuple<int, float, std::string>>();

现场演示

这篇关于c ++ 11:从模板函数构建std :: tuple的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆