C++ template specialization on functions

北城以北 提交于 2019-12-05 00:56:04

Partial specialization of function templates is not allowed. Herb Sutter explains why in his article "Why Not Specialize Function Templates?".

To work around this limitation you need to use class templates instead. You can then write a regular function template that uses that class template.

That specific error you're getting is because you forgot the second parameter in your specialization. If you this instead:

template<int length, typename T>
void test(T* array)
{
    //...
    test<length-1,T>(array);
}


template<typename T>
void test<0,T>(T* array)
{
    return;
}

GCC complains with the following:

error: function template partial specialization 'test<0, T>' is not allowed

Functions cannot be partially specialized. To work around this, have your template function call a function in a class:

template<int length, typename T>
struct helper
{
    static void go(T* array)
    {
        ...
        helper<length-1, T>::go(array);
    }
};

template<typename T>
struct helper<0, T>
{
    static void go(T* array)
    {
        ...
    }
};

template<int length, typename T>
void test(T* array)
{
    ...
    helper<length, T>::go(array);
}
NPE

Partial specialization of function templates is not allowed.

To work around that, you could make test a static member of a class template, and partially specialize the class.

You can workaround with a helper class. For illustrational purposes:

template<typename T, typename U> struct helper_t {
    static int foo () { return 0; }
};

template<typename T> struct helper_t<T,T> {
    static int foo () { return 1; }
};

template <typename T, typename U>
int frob () {
    return helper_t<T,U>::foo();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!