且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

函数的C ++模板专业化

更新时间:2023-11-02 18:27:52

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

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抱怨以下内容:


错误:功能模板部分专业化'test< 0,T>允许

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