通过 int 检索 variadic class 的给定成员
Retrieve given member of variadic class by int
这里是一个递归的class定义:
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
可能是个好主意。
这里是一个递归的class定义:
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
可能是个好主意。