Search code examples
c++templatesstdvector

How can I check if template type is any type of std::vector<>


I have a template function like this:

template <typename T> void MyClass::setData(const std::string& name, const T& value)
{
    ...
    
    // if the template type is a vector of strings, add instead of overwrite
    if constexpr (std::is_same_v<T, std::vector<std::string>>)
    {
        auto temp = someData.get<T>(name);
        temp.insert(temp.end(), value.begin(), value.end());

        someData.set(name, temp);
    }
    // otherwise just set data
    else
    {
       someData.set(name, value);
    }

    ...
}

What I want now is to check if T is any std::vector<>, not just for strings. How do I do that?


Solution

  • You can use partial specialization:

    #include <type_traits>
    #include <iostream>
    #include <vector>
    
    template <typename C> struct is_vector : std::false_type {};    
    template <typename T,typename A> struct is_vector< std::vector<T,A> > : std::true_type {};    
    template <typename C> inline constexpr bool is_vector_v = is_vector<C>::value;
    
    int main() {
        std::cout << is_vector_v< std::vector<int> > << "\n";
        std::cout << is_vector_v< int > << "\n";
    }