模板类成员函数的显式专门化 [英] explicit specialization of template class member function
问题描述
我需要专门针对某种类型的模板成员函数(让我们说 double )。它工作正常,而类 X
本身不是一个模板类,但当我做它的模板GCC开始给编译时错误。
#include< iostream>
#include< cmath>
template< class C> class X
{
public:
template< class T> void get_as();
};
template< class C>
void X< C> :: get_as< double>()
{
}
int main()
{
X< int> X;
x.get_as();
}
这里是错误信息
source.cpp:11:27:error:template-id
'get_as< double>'声明主模板
source.cpp:11 :6:error:prototype for
'void X< C> :: get_as()'不匹配类'X< C>'中的任何一个
source.cpp:7:35:error:candidate是:
template< class C> template< class T> void X :: get_as()
如何解决这个问题? p>
提前感谢。
您需要说明以下内容,但不正确
模板< class C&模板<>
void X< C> :: get_as< double>()
{
}
显式专门化的成员需要他们周围的类模板也明确专门化。所以你需要说下面,这将只专门为 X< int>
成员。
template<>模板<>
void X< int> :: get_as< double>()
{
}
如果你想保留周围的模板未特殊化,你有几个选择。我喜欢重载
模板< class C> class X
{
template< typename T> struct type {};
public:
template< class T> void get_as(){
get_as(type< T>(());
}
private:
template< typename T> void get_as(type< T>){
}
void get_as(type< double>){
}
};
I need to specialize template member function for some type (let's say double). It works fine while class X
itself is not a template class, but when I make it template GCC starts giving compile-time errors.
#include <iostream>
#include <cmath>
template <class C> class X
{
public:
template <class T> void get_as();
};
template <class C>
void X<C>::get_as<double>()
{
}
int main()
{
X<int> x;
x.get_as();
}
here is the error message
source.cpp:11:27: error: template-id
'get_as<double>' in declaration of primary template
source.cpp:11:6: error: prototype for
'void X<C>::get_as()' does not match any in class 'X<C>'
source.cpp:7:35: error: candidate is:
template<class C> template<class T> void X::get_as()
How can I fix that and what is the problem here?
Thanks in advance.
It doesn't work that way. You would need to say the following, but it is not correct
template <class C> template<>
void X<C>::get_as<double>()
{
}
Explicitly specialized members need their surrounding class templates to be explicitly specialized as well. So you need to say the following, which would only specialize the member for X<int>
.
template <> template<>
void X<int>::get_as<double>()
{
}
If you want to keep the surrounding template unspecialized, you have several choices. I prefer overloads
template <class C> class X
{
template<typename T> struct type { };
public:
template <class T> void get_as() {
get_as(type<T>());
}
private:
template<typename T> void get_as(type<T>) {
}
void get_as(type<double>) {
}
};
这篇关于模板类成员函数的显式专门化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!