I would like to specialize a function using a templated type but I am having trouble getting the desired results.
Consider the following simple example
#include <iostream>
#include <typeinfo>
#include <vector>
template <typename T>
void foo(){
std::cout << "In foo1 with type: " << typeid(T).name() << std::endl;
}
template< template<class, class...> class VEC, typename T>
void foo(){
std::cout << "In foo2 with vec type: " << typeid(VEC<T>).name()
<< " and template type: " << typeid(T).name() << std::endl;
}
int main() {
foo<int>();
foo<std::vector, int>();
foo<std::vector<int>>(); // Would like this to call the second version of foo
}
In foo1 with type: i
In foo2 with vec type: St6vectorIiSaIiEE and template type: i
In foo1 with type: St6vectorIiSaIiEE
Since you cannot specialize function templates partially, the usual approach is to use a helper class template:
template <typename T> struct X
{
static void f() { std::cout << "Primary\n"; }
};
template <template <typename...> class Tmpl, typename T>
struct X<Tmpl<T>>
{
static void f() { std::cout << "Specialized\n"; }
};
template <typename T> void foo() { X<T>::f(); }