c++ - 如何从元组中获取第 N 种类型?

标签 c++ templates c++11 stdtuple

我想制作一个模板,我可以在其中输入一个索引,它会给我那个索引的类型。我知道我可以用 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>

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++ - 如何从元组中获取第 N 种类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16928669/

相关文章:

c++ - 是否可以重新初始化 pdf 文件中的图形状态?

c++ - 非内联成员函数的模板类

c++ - 具有不同主体的方法的模板显式实例化

c++ - static_cast 指针类型的性能影响?

c++ - Facebook 桌面应用程序 C++

c++ - C 头文件中的函数声明与其在 .cpp 文件中的定义之间的一致性

visual-studio-2010 - 如何在非用户特定位置安装 Visual Studio 项目模板?

c++ - 具有原子变量的指针所有权

c++11 - 向量初始化的C++ 11向量

c++ - std::bind on member with call operator