关于函数的C++模板专业化

Ske*_*een 15 c++ templates template-specialization function-templates

我正在玩模板专业化,我发现了一个似乎无法解决的问题; 这是我的代码:

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

template<typename T>
void test<0>(T* array)
{
    return;
}
Run Code Online (Sandbox Code Playgroud)

所以我要做的就是传递模板中要处理的内容的长度.

问题是,编译这个,很好地输出:

a.cpp:83:43: error: template-id 'test<0>' in declaration of primary template
a.cpp: In function 'void test(T*) [with int length= -0x000000081, T = int]':
a.cpp:77:9:   instantiated from 'void test(T*) [with int length= -0x000000080, T = int]'
a.cpp:77:9:   instantiated from 'void test(T*) [with int length= -0x00000007f, T = int]'
a.cpp:77:9:   [ skipping 151 instantiation contexts ]
a.cpp:77:9:   instantiated from 'void test(T*) [with int length= 28, T = int]'
a.cpp:77:9:   instantiated from 'void test(T*) [with int length= 29, T = int]'
...
a.cpp: In function 'void test(T*) [with int length= -0x000000082, T = int]':
a.cpp:77:9:   instantiated from 'void test(T*) [with int length= -0x000000081, T = int]'
a.cpp:77:9:   instantiated from 'void test(T*) [with int length= -0x000000080, T = int]'
Run Code Online (Sandbox Code Playgroud)

最后两行与第一行几乎相同.

对我而言,它似乎没有抓住专业化,因此:

a.cpp:83:43: error: template-id 'test<0>' in declaration of primary template
Run Code Online (Sandbox Code Playgroud)

我对么?

如果我是正确的,我猜这是一个问题,即功能模板不允许部分模板特化,那么解决方案是什么,制作一个结构,并使用专门化呢?

R. *_*des 17

不允许对功能模板进行部分特化.Herb Sutter在他的文章"为什么不专门化功能模板?"中解释了为什么.

要解决此限制,您需要使用类模板.然后,您可以编写使用该类模板的常规函数​​模板.

您遇到的具体错误是因为您忘记了专业化中的第二个参数.如果你这样做:

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


template<typename T>
void test<0,T>(T* array)
{
    return;
}
Run Code Online (Sandbox Code Playgroud)

海湾合作委员会抱怨如下:

错误:不允许使用函数模板部分特化"test <0,T>"

  • 为什么不允许这样做?- 只是好奇. (2认同)

Dar*_*con 7

功能不能部分专业化.要解决此问题,请让您的模板函数在类中调用函数:

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);
}
Run Code Online (Sandbox Code Playgroud)