c++c++23c++-templates

Getting partial template types from nested templates


Give a series of nested template structs, I'd like to be able to extract the outer most template and "assign" it in a template using statement.

ie:

struct s0 { };

template<typename T>
struct s1 { };

template<typename T>
struct s2 { };

template<typename T>
using outer = ?????

Such that I can do:

outer<s1<s0>><int> //would be s1<int>
outer<s2<s1<s0>>><int> //would be s1<int>

I've got close by template member variable in a template struct, but I can't then "assign" that to a single using statement as it requires two levels of template statement.

Thanks in advance


Solution

  • You can create your traits with partial specialization. Usage is not outer<s1<s0>><int> but outer<s1<s0>, int>.

    Unsure of what you want for outer<s2<s1<s0>>, int>.

    So, if you want s2<int>, you might do:

    template <typename T, typename Inner>
    struct outer_impl;
    
    template <template <typename> class C, typename T, typename Inner>
    struct outer_impl<C<T>, Inner>
    {
        using type  = C<Inner>;
    };
    
    template <typename T, typename Inner>
    using outer = typename outer_impl<T, Inner>::type;
    

    Demo

    Or, if you want s2<s1<int>>, you might do:

    template <typename T, typename Inner>
    struct outermost_impl
    {
        using type = Inner;
    };
    
    template <template <typename> class C, typename T, typename Inner>
    struct outermost_impl<C<T>, Inner>
    {
        using type  = C<typename outermost_impl<T, Inner>::type>;
    };
    
    template <typename T, typename Inner>
    using outermost = typename outermost_impl<T, Inner>::type;
    

    Demo