简体   繁体   English

是否可以从模板参数中提取数组大小?

[英]Is it possible to extract array size from a template argument?

If this is a duplicate I apologize. 如果这是重复我道歉。 I looked around and found similar issues but nothing exactly like this. 我环顾四周,发现了类似的问题,但没有完全像这样。

If I instantiate a template like so... 如果我像这样实例化模板......

MyClass<int[10]> c;

How can I write the template to get access to both the type and the array size? 如何编写模板以访问类型和数组大小? I've tried everything I can think of and I can't get it. 我已经尝试了我能想到的一切,但我无法得到它。

I was inspired by the std::function template which lets you use similar syntax to the function prototype, like... 我受到std :: function模板的启发,它允许你使用与函数原型相似的语法,比如......

std::function<int(MyClass&)> myfunc;

So I thought it would be nice to have something similar for the array and its size. 所以我认为对阵列及其大小有类似的东西会很好。 I can use any of the newest c++ features (c++ 11/14). 我可以使用任何最新的c ++特性(c ++ 11/14)。

You can add a partial specialization which looks like this: 您可以添加如下所示的部分特化:

template <typename T, ptrdiff_t N>
class MyClass<T[N]>
{
};

Here's a demo . 这是一个演示

template<class Arr>
struct array_size {};
template<class T, size_t N>
struct array_size<T[N]>:std::integral_constant<std::size_t, N>{};
template<class Arr>
struct array_element {};
template<class Arr>
using array_element_t = typename array_element<Arr>::type;
template<class T, size_t N>
struct array_element<T[N]>{using type=T;};

now you can array_size<ArrType>{} and array_element_t<ArrType> without unpacking the type. 现在你可以在array_size<ArrType>{}包类型的情况下使用array_size<ArrType>{}array_element_t<ArrType>

template <typename T, typename = void>
struct deduce
{
};

template <typename T>
struct deduce<T,
  typename ::std::enable_if<
    ::std::is_array<T>{}
  >::type
>
{
  using value_type =
    typename ::std::decay<decltype(::std::declval<T>()[0])>::type;

  static constexpr auto size = sizeof(T) / sizeof(value_type);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM