c++arraystemplatessize-type

Idiomatic way to get size_type from std::array or the like


Triggered by this question, I came up with code along the line of (it was boost::array in my answer, but the same applies for std::array):

template <std::array<char,1>::size_type size>
void DataTransform(std::array<char, size> data) {

}

And I am not happy at all with <std::array<char,1>::size_type. I have to instantiate with a certain size, to know the size_type. For std::array I could have used size_t, but then what about the general case? What if size_type is not size_t? Or even more general (ie not for std::array) what if size_type is different for different sizes (silly but possible)?

I know this question is rather academic and there are many ways to avoid this "problem" completely (eg I could have passed iterators). Anyhow, I wonder...

What is a clean way to determine the size_type for templates that need a size (of type size_type) to be instantiated?

More generally, the question could be formulated as: How can I get my hands on a templates typedef that may depend on a template parameter before actually instantiating the template.


Solution

  • You can always use the specific type the template uses.

    std::array<T,N>::size_type doesn't denote the type of N, that's always std::size_t .

    template <class T, size_t N> struct array
    

    Even in the general case, the type of N doesn't depend on any part of the instantiation of some_template<N>, because it's part of the declaration of some_template.