Accepting any type of STL container and using its value type

I have a function that works with an STL container of any type and needs to pass the container element type to another template function. Actually, when I talk about the type of container, I really don't mean it. Strictly only vectors and arrays. I have something like this:

template <typename T> int ProcessData(T data) { return DoInternalProcessing<T::value_type>(data.data(), data.size()); } 

MSVC11 accepts this code, but gcc does not. What is wrong with it? For gcc, I thought that the type of the value should be a parameter, but then it will require the caller to specify T (container type), which will be very cumbersome using std :: array, and this main function is designed to provide a very simple interface that abstracts from the underlying data.

+4
source share
1 answer

Since T::value_type is a dependent type, you need typename T::value_type .

This will not work with the array: the array will not provide a typedef from value_type , as vector does.

The usual way to handle this is to accept a couple of iterators (or pointers if the underlying β€œcollection” is an array). In this case, you can use std::iterator_traits<T>::value_type to get the type of the value the iterator belongs to. This will work with raw pointers, so (for example) std::iterator_traits<int *>::value_type will give int .

If you really need to use a container (and auxiliary arrays), you can use std::begin(data) to get an iterator at the beginning of the data, and then use std::iterator_traits<T>::value_type to get the std::iterator_traits<T>::value_type .

+7
source

Source: https://habr.com/ru/post/1482788/


All Articles