如何从元组中获得第n个类型
How to get N-th type from a tuple?
我想做一个模板,我可以输入一个索引,它会给我在该索引的类型。我知道我可以用decltype(std::get<N>(tup))
做这个,但我想自己实现它。例如,我想这样做,
typename get<N, std::tuple<int, bool, std::string>>::type;
…它会给我位置N - 1
的类型(因为数组从0开始索引)我怎么做呢?谢谢。
这种特性已经存在,它被称为std::tuple_element
。
下面是一个的实例来演示它的用法。
#include <tuple>
#include <type_traits>
int main()
{
using my_tuple = std::tuple<int, bool, char>;
static_assert(std::is_same<std::tuple_element<0, my_tuple>::type, int>::value, "!");
static_assert(std::is_same<std::tuple_element<1, my_tuple>::type, bool>::value, "!");
static_assert(std::is_same<std::tuple_element<2, my_tuple>::type, char>::value, "!");
}
您可以使用类模板和部分专门化来做您想做的事情。(注意,std::tuple_element
几乎与另一个答案相同):
#include <tuple>
#include <type_traits>
template <int N, typename... Ts>
struct get;
template <int N, typename T, typename... Ts>
struct get<N, std::tuple<T, Ts...>>
{
using type = typename get<N - 1, std::tuple<Ts...>>::type;
};
template <typename T, typename... Ts>
struct get<0, std::tuple<T, Ts...>>
{
using type = T;
};
int main()
{
using var = std::tuple<int, bool, std::string>;
using type = get<2, var>::type;
static_assert(std::is_same<type, std::string>::value, ""); // works
}
相关文章:
- 在C++中,如何通过几种类型从元组中选择多个元素
- 将元组类型扩展为可变参数模板?
- 时间复杂度 当具有复合数据类型(如元组或对)时?
- 创建派生自可变参数模板包的类型元组
- 枚举元组类型的最佳方法?
- 我无法在用forward_as_tuple创建的元组中按类型访问元素
- Boost.Hana:在 constexpr 上下文中将值元组转换为相应类型的元组
- 在C++中返回基元类型数组(Java比较)
- 将函数应用于元组中的每个元素,将每个元素强制转换为类型包中的不同类型,然后作为参数包传递
- 如何将值元组中的相应值附加到相同类型的向量元组中
- 您自己的类型的结构化绑定,不是结构或元组(通过公共成员函数)
- 如何在编译器时动态获取元组内的变量类型C++?
- 验证(使用 static_assert)元组类型是否遵循某种顺序(有状态编译时检查)
- 使用每种类型的可变参数模板上的类模板初始化元组
- 在 c++17 中筛选类型元组
- 有没有办法将一对元组剥离为可变参数模板类型或实例化具有可变参数类型的东西?
- 从类型元组到通过调用模板函数返回的值数组
- 为什么不采用非类型部分专用元组?
- 以后可以解压缩类型元组吗?
- 如何根据表达式在Boost.Hana中是否有效来过滤类型元组