函数的C ++模板专业化 [英] C++ template specialization on functions

查看:165
本文介绍了函数的C ++模板专业化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm playing around with template specialization, and I've found an issue I can't seem to solve; this is my code:

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

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

所以我想做的是传递长度

So what I'm trying to do, is to pass the length, of what's to be processed in the template.

问题是,编译的这个,well输出永远:

The problem is, that the compilation of this, well outputs forever:

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]'

最后两行,与第一行相同。

Last two lines, is pretty much the same as the first ones.

对我来说,它不会捕捉到特殊化,因此:

To me it would seem, its not catching the specialization, hence:

a.cpp:83:43: error: template-id 'test<0>' in declaration of primary template

我是否正确?

'm猜测这是问题,部分模板专门化不允许函数模板,那么什么解决方案,然后,使一个结构,并使用专门化。

And if I'm correct, I'm guessing it's the issue that partial template specialisation is not allowed for function templates, so what would be the solution then, making a struct, and using specialisation on that?

推荐答案

不允许对函数模板进行部分特殊化。 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

这篇关于函数的C ++模板专业化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆