c++templatestemplate-meta-programming

How to replace a template parameter in a given type?


Given that a template parameter called B is of type C<D> (on instantiation), how can I construct C<A> from B?

Here is a minimalized extract from my code:

template<typename A>
class foo {
    template<typename B> // B is guaranteed to always be of the form C<D>
    // How to write a function here with return type C<A>?
}

Solution

  • you can do this with template specialization of a template template parameter

    template<typename, typename>
    struct meta {};
    
    template<typename A, template<typename> typename C, typename B>
    struct meta<A, C<B>> {
        using type = C<A>;
    };
    

    meta<A, C<B>>::type will be C<A>

    if you want to have handling of default argument in basic cases

    template<typename...>
    struct meta {};
    
    template<typename A, template<typename...> typename C, typename B, typename ... Ts>
    struct meta<A, C<B, Ts...>> {
        using type = C<A, Ts...>;
    };