从以下示例开始:
#include <cstdio>
template<int X, int Y>
struct C {
template<int Z> void bar() {printf("Generic %d/%d\n",X,Y);}
void foo() {bar<Y>();}
};
int
main(int argc, char *argv[])
{
C<0,0> c0;
c0.foo();
C<0,1> c1;
c1.foo();
}
现在我想定义额外的“bar”函数,专门用于“y”的值。特别是下面插入的行(抱歉,我不知道如何突出显示它们):
#include <cstdio>
template<int X, int Y>
struct C {
template<int Z> void bar() {printf("Generic %d/%d\n",X,Z);}
template<> void bar<1>() {printf("Special %d/1\n",X);}
void foo() {bar<Y>();}
};
template<int X> template<> C<X,2>::bar<2>() {printf("Special %d/2\n",X);}
int
main(int argc, char *argv[])
{
C<0,0> c0;
c0.foo();
C<0,1> c1;
c1.foo();
}
遗憾的是,这两种方法似乎都无效/compile(GCC/9.3.0,-std=C++11)。例如:
tempspec.cpp:94:12: error: explicit specialization in non-namespace scope ‘struct C<X, Y>’
94 | template<> void bar<1>() {printf("Special %d/1\n",X);}
| ^
tempspec.cpp:94:26: error: template-id ‘bar<1>’ in declaration of primary template
94 | template<> void bar<1>() {printf("Special %d/1\n",X);}
| ^
tempspec.cpp:97:33: error: expected initializer before ‘<’ token
97 | template<int X> void C<X,2>::bar<2>() {printf("Special %d/2\n",X);}
| ^
我知道我不能部分专门化一个函数(这是我真正想做的),但我认为这里我是部分专门化结构,完全专门化函数。
那么问题来了,我如何定义作为成员函数的“bar”的附加规范呢?
(至于为什么,假设“bar”是模具计算,而“y”是模具的大小。基于“y”,我可能有针对某些大小优化的不同实现。)
直接做你想做的事情需要对函数进行部分专门化,这是不允许的。一种替代方法是让主模板中的bar函数服从于您可以覆盖的另一个函数。