Search code examples
c++listvectortypeidtypeinfo

Check for container type


How can I check for a type of container? I.e.

template <class Container1>
void func (Container1 &cont_1)
{
  if (cont_1 is list container)
    //do stuff
  if (cont_1 is vector container)    
    //do other stuff
}

The only two possibilities I have are list and vector. Note that I don't know the type of values within list/vector, i.e. vector<char> or vector<int>, etc. is possible, thus I just want to get the information of getting a vector or a list. I came across typeid and type info, but did not really get it done.


Solution

  • You can use function overloading to achieve that:

    template<typename T>
    void func(std::vector<T>& vec)
    {
        //Do something with vector
    }
    
    template<typename T>
    void func(std::list<T>& list)
    {
        //Do something with list
    }
    

    Or using typeid, which is probably less than ideal, because the code in either case would have to be compilable for both std::vector and std::list, as templates are known at compile time, and even though the branch might not execute on a std::list, the compiler doesn't know this at that point, and so it will fail to compile, trying to apply a std::vector operation on a std::list.

    template<template<typename, typename> class C, typename T, typename Alloc>
    void func(C<T, Alloc>& container)
    {
        if (typeid(container).hash_code() == typeid(std::vector<T, Alloc>&).hash_code())
            ; //Do something with vector
        else if (typeid(container).hash_code() == typeid(std::list<T, Alloc>&).hash_code())
            ; //Do something with list
    }