Check at compile-time is a template type a vector

c++, templates

Solution

It is named tag dispatching :

#include <vector>
#include <set>
#include <type_traits>

template<typename T> struct is_vector : public std::false_type {};

template<typename T, typename A>
struct is_vector<std::vector<T, A>> : public std::true_type {};

template <typename T>
class X {
    T container;

    void foo( std::true_type ) {
        container.push_back(0);
    }
    void foo( std::false_type ) {
        container.insert(0);
    }
public:
    void foo() {
        foo( is_vector<T>{} );
    }
};

// somewhere else...
int main() {
    X<std::vector<int>> abc;
    abc.foo();

    X<std::set<int>> def;
    def.foo();
}

Problem

I can imagine the following code: ``` template <typename T> class X { public: T container; void foo() { if(is_vector(T)) container.push_back(Z); else container.insert(Z); } } // somewhere else... X<std::vector<sth>> abc; abc.foo(); ``` How to write it, to successfully compile? I know type traits, but when I'm defining: ``` template<typename T> struct is_vector : public std::false_type {}; template<typename T, typename A> struct is_vector<std::vector<T, A>> : public std::true_type {}; ``` It doesn't compile: ``` error: no matching function for call to 'std::vector<sth>::insert(Z)' ``` static_assert also isn't that what I'm looking for. Any advices? Here's a short example of what I want to achieve (SSCCE): http://ideone.com/D3vBph

Original source