get_element_by_type

Posted abelian

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了get_element_by_type相关的知识,希望对你有一定的参考价值。

#include <iostream>
#include <string>
#include <tuple>  
template <class T, std::size_t N, class... Args>
struct indexOf
{
    static constexpr auto value = N;
};
template <class T, std::size_t N, class... Args>
struct indexOf<T, N, T, Args...>
{
    static constexpr auto value = N;
};
template <class T, std::size_t N, class U, class... Args>
struct indexOf<T, N, U, Args...>
{
    static constexpr auto value = indexOf<T, N + 1, Args...>::value;
};
/*
template <class T, std::size_t N>
struct indexOf<T, N>
{
    static constexpr auto value = -1;
    static_assert(value!=-1, "the type is not exist");
};
*/
template <class T, class... Args>
T get_element_by_type(const std::tuple<Args...>& t)
{
    return std::get<indexOf<T, 0, Args...>::value>(t);
}
int main()
{
std::tuple<int, double, char, short> tp = std::make_tuple(1, 2.3, ‘A‘, 1);
auto r = get_element_by_type<double>(tp);
std::cout<<r<<std::endl;
}

以上是关于get_element_by_type的主要内容,如果未能解决你的问题,请参考以下文章