首页 > 代码库 > get_element_by_type

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 = http://www.mamicode.com/N;
};
template <class T, std::size_t N, class... Args>
struct indexOf<T, N, T, Args...>
{
    static constexpr auto value = http://www.mamicode.com/N;
};
template <class T, std::size_t N, class U, class... Args>
struct indexOf<T, N, U, Args...>
{
    static constexpr auto value = http://www.mamicode.com/indexOf::value;
};
/*
template <class T, std::size_t N>
struct indexOf<T, N>
{
    static constexpr auto value = http://www.mamicode.com/-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