为模板化类专门化模板化函数 在C++中,我试图为模板本身的模板化一个模板化函数。
以下是一个基本示例: 测试h:为模板化类专门化模板化函数 在C++中,我试图为模板本身的模板化一个模板化函数。,c++,templates,template-specialization,C++,Templates,Template Specialization,以下是一个基本示例: 测试h: 模板 myC类{ tx; }; 模板 无效f(U y){ } 模板 模板 无效f(myC y){ } test.cpp #include "test.h" int main() { myC<double> m; f(m); } #包括“test.h” int main(){ myC m; f(m); } GCC 4.6.1给出了以下错误消息: In file included from test.cpp:1:0: test.h:1
模板
myC类{
tx;
};
模板
无效f(U y){
}
模板
模板
无效f(myC y){
}
test.cpp
#include "test.h"
int main() {
myC<double> m;
f(m);
}
#包括“test.h”
int main(){
myC m;
f(m);
}
GCC 4.6.1给出了以下错误消息:
In file included from test.cpp:1:0:
test.h:13:25: error: too many template parameter lists in declaration of ‘void f(myC<T>)’
test.h:13:6: error: template-id ‘f<myC<T> >’ for ‘void f(myC<T>)’ does not match any template declaration
test.h:13:25: note: saw 2 ‘template<>’, need 1 for specializing a member function template
test.cpp:1:0中包含的文件中的:
test.h:13:25:错误:“void f(myC)”声明中的模板参数列表太多
test.h:13:6:错误:“void f(myC)”的模板id“f”与任何模板声明都不匹配
test.h:13:25:注意:SAW2“模板”,需要1专门化成员函数模板
这有可能吗?还是有其他方法可以实现同样的目标?据我所知,您不能专门化模板函数,只能专门化模板类(或结构) 但这并不是一个限制:只需声明一个具有静态公共成员函数的结构,并将模板参数指定给该结构:
template <class T>
class myC {
T x;
};
template <class U>
struct Foo
{
static void f(U y) {
}
};
template <>
template <class T>
struct Foo<myC<T> >
{
static void f(myC<T> y) {
}
};
模板
myC类{
tx;
};
模板
结构Foo
{
静态空隙f(U-y){
}
};
模板
模板
结构Foo
{
静态空隙f(myC y){
}
};
缺点是类模板不能自动求解模板参数。但这可以通过函数模板轻松解决,类似于原始模板:
template <class U>
void f(U y) {
return Foo<U>::f(y);
}
模板
无效f(U y){
返回Foo::f(y);
}
模板
模板
无效f(myC y){
}
您试图在这里做的是所谓的部分专门化,这在函数模板的情况下是不允许的
函数模板要么完全专用,要么根本不专用。语言规范不允许函数模板的部分专门化
因此,您可以将函数模板重载为:
template <class T>
void f(myC<T> y) //note that it is overload, not specialization
{
}
模板
void f(myC y)//注意它是重载,而不是专门化
{
}
这是允许的,甚至优于模板的完全专门化
阅读Herb Sutter的以下文章:
template <class U> void f(U y) {}
template<> void f<double>(double y) {} // specialization for double
template void f(U y){
模板void f(双y){}//双y的专门化
请注意,如果可以从上下文推导模板参数,则无需显式指定该参数:
template<> void f<>(int y) {} // specialization for int
template void f(int y){}//int的专门化
在您的情况下,完全专门化是不可能的,因为函数参数是一个模板类。但是,与任何函数一样,模板函数也可以重载。在您的情况下,它将是这样的:
template <class T>
class myC {
T x;
};
template <class U>
void f(U y) {
}
template <class T>
void f(myC<T> y) {
}
int main() {
myC<double> m;
f(m);
return 0;
}
模板
myC类{
tx;
};
模板
无效f(U y){
}
模板
无效f(myC y){
}
int main(){
myC m;
f(m);
返回0;
}
它不是在C++11中引入的吗?
template<> void f<>(int y) {} // specialization for int
template <class T>
class myC {
T x;
};
template <class U>
void f(U y) {
}
template <class T>
void f(myC<T> y) {
}
int main() {
myC<double> m;
f(m);
return 0;
}