How to determine the data type in a generic container searching function

153 Views Asked by At

I am mainly a C developer, but starting to use C++ more and more.

I have a templated function below which will search for values in STL containers of different types and do some processing.

I understand that the compiler will generate different functions depending on which data types are passed.

How do I determine the element type here in my situation? I can't use auto because my code should be compiled without the C++11 flag.

template <typename T, typename T_it>
void ProcessContainer(T con, T_it it )
{
    typename N;
    for (it = con.begin(); it != con.end(); ++it )
    {
        //auto element  = *it; - Can't use auto in my case
        // other processing.. not included
    }
} 
2

There are 2 best solutions below

5
NathanOliver On

The standard containers have a type member name value_type that represents the type of the elements in the container and you can use that to create your object like

template <typename T, typename T_it>
void ProcessContainer(T con, T_it it )
{
    for (it = con.begin(); it != con.end(); ++it )
    {
        typename T::value_type element = *it;
    }
} 

There is also std::iterator_traits that will also give you the type that the iterator points to and that would be used like

template <typename T, typename T_it>
void ProcessContainer(T con, T_it it )
{
    for (it = con.begin(); it != con.end(); ++it )
    {
        typename std::iterator_traits<T_it>::value_type element = *it;
    }
} 
1
Dmytro Ovdiienko On

Another option is you can split your function into several functions and let compiler to deduct the element type:

template<typename El>
void ProcessOne(El const& el)
{
    // other processing.. not included
    std::cout << el << std::endl;
}

template<typename It>
void ProcessContainer(It begin, It end)
{
    while(begin != end)
    {
        ProcessOne(*begin);
        ++begin;
    }
}

template <typename Container>
void ProcessContainer(Container const& con)
{
    ProcessContainer(con.begin(), con.end());
}

However from my point of view the solution provided by @NathanOliver is better.