2012-02-17 73 views
2

在C++中,我正在尝试为模板化对象专门化模板化函数。为模板类专门化模板函数

这是一个基本的例子: test.h:

template <class T> 
class myC { 
    T x; 
}; 

template <class U> 
void f(U y) { 
} 

template <> 
template <class T> 
void f<myC<T> >(myC<T> y) { 
} 

TEST.CPP

#include "test.h" 
int main() { 
    myC<double> 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 

这是可能吗?还是有另一种方法来实现相同的目标?

回答

2

不能专门的模板功能;只有模板类可以是专门的。 编辑:Nawaz的回答是正确的:它是部分专业化,不允许用于模板功能,仅适用于类。一个完整的专业化是可能的:

template <class U> void f(U y) {} 
template<> void f<double>(double y) {} // specialization for double 

注意,模板参数不必明确指明,如果它可以从上下文推断:

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; 
} 
0

据我所知,你不能专门化模板功能,只能模板类(或结构)。

但是,这是很难的限制:只需要声明静态公共成员函数的结构和MAVE模板参数的结构:

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) { 
    } 
}; 

的缺点是,类模板不会自动解决模板参数。但是,可以用函数模板easlily解决,类似于原始之一:

template <class U> 
void f(U y) { 
    return Foo<U>::f(y); 
} 
4
template <> 
template <class T> 
void f<myC<T> >(myC<T> y) { 
} 

什么你atttempting在这里做的是叫做部分专业化未在功能允许的情况下,模板。

功能模板是完全专门的,或根本不专门。语言规范不允许功能模板的部分专业化。

这样你就可以超载函数模板为:

template <class T> 
void f(myC<T> y) //note that it is overload, not specialization 
{ 
} 

这是允许的,并且优于模板甚至完全专业化。

阅读香草萨特这些文章:

+0

是不是它在C++ 11中引入? – 2012-02-17 19:51:54