acorso acorso - 3 years ago 231
C++ Question

How to specialize for template template arguments

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<std::vector, int>();
foo<std::vector<int>>(); // Would like this to call the second version of foo

The output of which is

In foo1 with type: i
In foo2 with vec type: St6vectorIiSaIiEE and template type: i
In foo1 with type: St6vectorIiSaIiEE

Is there a way to write a template signature for the second version of foo that would be used for the last invocation of foo (with the std::vector template parameter)?


Answer Source

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(); }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download