Search code examples
c++templatespartial-specialization

How to specialize template function with template types


Is it possible to specialize a template function for template types? I don't know if my terminology is correct, so I'll provide a simple sample with what I want to achieve:

#include <vector>
#include <string>
#include <iostream>

template<typename T>
void f()
{
    std::cout << "generic" << std::endl;
}

template<>
void f<std::string>()
{
    std::cout << "string" << std::endl;
}

template<typename T>
void f<std::vector<T>>()
{
    std::cout << "vector" << std::endl;
}

int main()
{
    f<double>();
    f<std::string>();
    f<std::vector<int>>();

    return 0;
}

This code doesn't compile. VS2013 gives me

error C2995: 'void f(void)' : function template has already been defined

on this function:

template<typename T>
void f<std::vector<T>>()
{
    std::cout << "vector" << std::endl;
}

How may I achieve this behavior? It's very important to have type f(void) signature. Is this code falling into partial specialization for functions(forbidden in C++)?


Solution

  • You can't partially specialize template function, but you can for template class. So you can forward your implementation to a dedicated class. Following may help: (https://ideone.com/2V39Ik)

    namespace details
    {
        template <typename T>
        struct f_caller
        {
            static void f() { std::cout << "generic" << std::endl; }
        };
    
        template<>
        struct f_caller<std::string>
        {
            static void f() { std::cout << "string" << std::endl; }
        };
    
        template<typename T>
        struct f_caller<std::vector<T>>
        {
            static void f() { std::cout << "vector" << std::endl; }
        };
    }
    
    template<typename T>
    void f()
    {
        details::f_caller<T>::f();
    }