Implementing std::rank for other containers

*爱你&永不变心* 提交于 2019-12-08 07:44:32

问题


Explanation :

std::rank just works for c style array .

So I implemented similar rank for std::vector which works fine :

#include <iostream>
#include <vector>

template<typename Type, Type val>
  struct integral_constant
  {
    static constexpr Type value =val;
  };

  template<typename>
    struct rank
    : public integral_constant<std::size_t, 0> { };

  template<typename Type>
    struct rank< std::vector<Type> >
    : public integral_constant<std::size_t, 1 + rank<Type>::value> { };

    template<class T>
   constexpr size_t vector_dimentions(T)
    {
         return rank<T>::value ;
    }

int main()
{
    std::vector<std::vector<std::vector<int>>> vec;
    std::cout<<vector_dimentions(vec) << '\n';
}

ideone

Problem :

Now I want to generalize it for other containers like std::list ,...

So I change the struct definition to :

  template<template<typename>class Container,typename Type>
    struct rank< Container<Type> >
    : public integral_constant<std::size_t, 1 + rank<Type>::value> { };

ideone

But now It gives wrong answer(always 0) !

I think in this case it can't deduce the right struct because it has now 2 template parameter . is it correct ?! How can I solve that ?


回答1:


With help of KerrekSB I found the solution :

template <typename> struct prank : std::integral_constant<std::size_t, 0> {};

template <template <typename...> class C, typename ...Args>
struct prank<C<Args...>>
: std::integral_constant<
    std::size_t,
    1 + prank<typename C<Args...>::value_type>::value> {};

template <typename U, typename V>
struct prank<std::pair<U, V>>
: std::integral_constant<std::size_t, 1 + prank<V>::value> {};

template <typename... Args>
struct prank<std::tuple<Args...>>
: std::integral_constant<std::size_t, 1> {};

template <typename T,typename... Args>
struct prank<std::tuple<T,Args...>>
: std::integral_constant<std::size_t, prank<T>::value+prank<std::tuple<Args...>>::value> {};

ideone



来源:https://stackoverflow.com/questions/24222427/implementing-stdrank-for-other-containers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!