通过int检索可变类的给定成员

Retrieve given member of variadic class by int

本文关键字:成员 int 检索 通过      更新时间:2023-10-16

这是一个递归类定义:

template<class... T>
class Mgr2
{
};
template<class T, class... args>
class Mgr2<T, args...>
{
  Container<T> _container;
  Mgr2<args...> _tail;
public:
  Mgr2() { };
};

我想实现以下内容:

Mgr2<int, double> mgr;
mgr.get<0>(); // retrieves the Container<int> element

我怎么能这么做?

#include <type_traits>
template<class T>
struct Container {};
template<class... T>
class Mgr2
{
};
template<class T, class... args>
class Mgr2<T, args...>
{
  Container<T> _container;
  Mgr2<args...> _tail;
  template<int idx>
  auto _get(std::integral_constant<int, idx>) const
    -> decltype(_tail.template get<idx-1>())
  { return _tail.get<idx-1>(); }
  const Container<T> &_get(std::integral_constant<int, 0>) const
  { return _container; }
public:
  Mgr2() { };
  template<int idx>
  auto get() const -> decltype(this->_get(std::integral_constant<int, idx>()))
  { return _get(std::integral_constant<int, idx>()); }
};
int main()
{
  Mgr2<int, double> mgr;
  mgr.get<0>(); // retrieves the Container<int> element
}

看看std::tuple可能是个好主意。