lezebulon
lezebulon

Reputation: 7994

Retrieve given member of variadic class by int

here is a recursive class definition :

template<class... T>
class Mgr2
{

};

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

I'd like to implement the following :

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

How could I do this?

Upvotes: 0

Views: 34

Answers (1)

ex-bart
ex-bart

Reputation: 1372

#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
}

It is probably a good idea to look at std::tuple, though.

Upvotes: 3

Related Questions