为其他容器实现std :: rank [英] Implementing std::rank for other containers

查看:82
本文介绍了为其他容器实现std :: rank的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说明:

std :: rank 仅适用于c样式数组.

std::rank just works for c style array .

所以我为std::vector实现了类似的rank,效果很好:

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

问题:

现在,我想将其推广到其他容器,例如std::list,...

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

但是现在它给出了错误的答案(总是0)!

But now It gives wrong answer(always 0) !

我认为在这种情况下它无法推断出正确的结构,因为它现在具有2个template参数.这是正确的吗 ?!我该如何解决?

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 ?

推荐答案

KerrekSB 的帮助下,我找到了解决方案:

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

这篇关于为其他容器实现std :: rank的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆