如何获取内部类的父类型

时间:2014-06-13 09:42:36

标签: c++

struct Parent
{
 struct Inner
 {
 }
};

void foo()
{
 bar<Parent::Inner>();
} 

template<class T>
void bar()
{
 //here I would like to get the type of T class' parent
}

在上面的代码中,是否可以不编写协议或在Inner类中放入typedef来获取父类内部类的类型?

2 个答案:

答案 0 :(得分:2)

如果不使用typedefusing,则无法访问容器的类型。但是,您可以专门使用bar函数来了解容器的类型。

template<> void bar<Parent::Inner>()
{
  // Here, you know what the parent is
}

答案 1 :(得分:1)

使用简单的using

struct Parent
{
  struct Inner
  {
    using parent_type = Parent;
  };

};

template<class T>
void bar()
{
  //here I would like to get T's parent type
  typename T::parent_type t;
}

另请注意,bar<Inner>();格式不正确。你需要

bar<Parent::Inner>();