Is it possible to extract an array from a template argument?

If this is a duplicate, I apologize. I looked around and found similar problems, but nothing of the kind.

If I create a template this way ...

MyClass<int[10]> c; 

How can I write a template to access the type and size of an array? I tried everything I could, and I can’t get it.

I was inspired by the std :: function template, which allows you to use the same syntax for a function prototype, for example ...

 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 latest C ++ features (C ++ 11/14).

+7
c ++ c ++ 11 templates template-meta-programming
source share
3 answers

You can add a partial specialization that looks like this:

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

Here is a demo .

+17
source share
 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.

+3
source share
 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); }; 
+2
source share

All Articles