Search code examples
c++templatesnested-class

how to get outer class name from inner enum


basicly what i want to do is written in code. so , is there a way with templates or with something else get outer class name in global function ? is there a way to get this code work?

#include <iostream>

class A
{
public:
    enum class B
    {
        val1, 
        val2
    };
    typedef B InnerEnum;
    static void f(InnerEnum val)
    {
        std::cout << static_cast<int>(val);
    }
};

template <typename T1>
void f(typename T1::InnerEnum val)
{
    T1::f(val);
}
int main()
{
    A::InnerEnum v = A::InnerEnum::val1;
    f(v);
    return 0;
}

Solution

  • You may create trait for that and manually feed it:

    template <typename T>
    struct outer_class;
    
    template <>
    struct outer_class<A::B> { using type = A;};
    

    And then

    template <typename E>
    void f(E val)
    {
        using T = typename outer_class<E>::type;
        T::f(val);
    }