How can I get the innermost template parameter type?

后端 未结 2 661
猫巷女王i
猫巷女王i 2020-12-21 01:26

Q

In a dummy example of a class

typedef myStruct>> mv;

int is the innermost

相关标签:
2条回答
  • 2020-12-21 01:56

    Building on 0x499602D2's answer, we get the following to only consider the first template parameter if ever there are several. And yes it compiles. It's also slightly simpler.

    #include <tuple>
    #include <type_traits>
    #include <vector>
    
    template<typename T>
    struct innermost_impl
    {
        using type = T;
    };
    
    template<template<typename...> class E, typename Head, typename... Tail>
    struct innermost_impl<E<Head, Tail...>>
    {
        using type = typename innermost_impl<Head>::type;
    };
    
    template<typename T>
    using innermost = typename innermost_impl<T>::type;
    
    template<class>
    struct X;
    
    static_assert(std::is_same<innermost<X<X<X<int>>>>, int>::value, "");
    
    static_assert(
        std::is_same<innermost<std::vector<X<std::vector<int>>>>, int>::value,
        ""
    );
    
    int main()
    {
    }
    

    Note that no attempt is made to validate that the same template is used over and over.

    0 讨论(0)
  • 2020-12-21 01:58

    Try the following. It also returns a tuple if the template has more than one element:

    #include <tuple>
    #include <type_traits>
    
    template<typename T>
    struct innermost_impl
    {
        using type = T;
    };
    
    template<template<typename> class E, typename T>
    struct innermost_impl<E<T>>
    {
        using type = typename innermost_impl<T>::type;
    };
    
    template<template<typename...> class E, typename... Ts>
    struct innermost_impl<E<Ts...>>
    {
        using type = std::tuple<typename innermost_impl<Ts>::type...>;
    };
    
    template<typename T>
    using innermost = typename innermost_impl<T>::type;
    
    template<class>
    struct X;
    
    static_assert(std::is_same<innermost<X<X<X<int>>>>, int>::value, "");
    
    int main()
    {
    }
    
    0 讨论(0)
提交回复
热议问题