Search code examples
c++templatestype-traitstype-deduction

Deduce outer type from inner type parameter


Given struct outer { struct inner { }; }, I want to deduce the outer type from a parameter having the inner type:

template <typename T>
void f(T t) { ... }

f(outer::inner p)
{
    // deduce typename 'outer' here
}

Assume that all outer of interest have an inner named inner.


Solution

  • As alternative, you may create a traits that you feed manually:

    template <typename T> struct outer_type;
    
    template <> struct outer_type<outer::inner> { using type = outer; };
    // ... other specialization for each outer::inner types
    

    And then:

    template <typename T>
    void f(T t)
    {
        using outer = typename outer_type<T>::type;
        // ...
    }