0

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?

el.mojito
  • 170
  • 1
  • 10
  • `template < template typename T >`, something like that maybe. – kiner_shah Jun 30 '22 at 11:03
  • Could be more generic if it would take any container that has a `begin` and `end`, rather than just `vector`. (That being said, I ♥︎ `vector`.) – Eljay Jun 30 '22 at 11:11
  • 1
    You could use overloads for this: https://gcc.godbolt.org/z/d7Mo4zEsK – Simon Kraemer Jun 30 '22 at 11:12
  • the duplicate questions already has a `is_vector` type trait while it is missing `if constexpr` while this question already has `if constexpr` but misses the trait. Hence, imho its not a good duplicate – 463035818_is_not_an_ai Jun 30 '22 at 11:31

1 Answers1

1

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";
}
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185