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

Time:03-16

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
    }
} 

CodePudding user response:

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;
    }
} 

CodePudding user response:

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

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

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

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

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

  • Related