[英]Template member function specialization
I have this: 我有这个:
//forward declaration
template<typename Elem, int D1 = 1, int D2 = 1, int D3 = 1>
class matrix;
template<typename Elem, int D1, int D2, int D3>
struct matrix_deref_type_trait
{
typedef matrix<Elem, D2 == 1 ? 1 : D1, D3 == 1 ? 1 : D2, 1> matrix_deref;
};
template<typename Elem, int D1>
struct matrix_deref_type_trait<Elem, D1, 1, 1>
{
typedef Elem matrix_deref;
};
template<typename Elem, int D1, int D2, int D3>
class matrix:public object
{
public:
typedef typename matrix_deref_type_trait<Elem, D1, D2, D3>::matrix_deref matrix_deref;
inline matrix_deref operator[](int J)
{
...
}
}
And want to specialize a case for the operator[] (outside the class body): 并且想要专门为运算符[](在类体外)的情况:
template<typename Elem, int D1>
typename matrix<Elem, D1, 1, 1>::matrix_deref matrix<Elem, D1, 1, 1>::operator[](int J)
{
return M_ptr[J];
}
But I'm getting this error: 但是我收到了这个错误:
error C2244: 'matrix<Elem,D1,D2,D3>::operator []' : unable to match function definition to an existing declaration
Can I override this member function without full specialization of the whole class? 如果没有全班的完全专业化,我可以覆盖这个成员函数吗? What should I do? 我该怎么办? Thanks. 谢谢。
You cannot specialize a non-template method of a template class. 您不能专门化模板类的非模板方法。 You can only specialize a template class itself. 您只能专门化模板类本身。 Or you can specialize template method of any (template or non-template class). 或者您可以专门化任何模板方法(模板或非模板类)。
Specializing non-template method of a template class makes no sense: compiler needs to know how the whole class looks. 专门用于模板类的非模板方法毫无意义:编译器需要知道整个类的外观。 And you're just telling: hey, I don't care about the class, but what I know is how this one method will look like. 而你只是在告诉:嘿,我不关心课程,但我所知道的是这种方法的样子。
just specialize you matrix class : 只是专门为矩阵类:
template<typename Elem, int D1>
class matrix<Elem,D1,1,1>
{
public:
typedef typename matrix_deref_type_trait<Elem, D1, 1, 1>::matrix_deref matrix_deref;//this line
inline matrix_deref operator[](int J)
{
std::cout << "special\n";
}
};
also you dont need to do the ?:
check in trait class, because if D2
and D3
are 1
it will always choose the trait specialization. 你也不需要做?:
检查特质类,因为如果D2
和D3
为1
,它将始终选择特征专业化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.