c++模板部分特化成员函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15374841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
c++ template partial specialization member function
提问by Simon Righley
I'm new to templates so maybe this is a trivial thing but I cannot get it to work. I'm trying to get partial specialization of a class member function. The shortest code would be:
我是模板的新手,所以也许这是一件微不足道的事情,但我无法让它工作。我正在尝试获得类成员函数的部分专业化。最短的代码是:
template <typename T, int nValue> class Object{
private:
T m_t;
Object();
public:
Object(T t): m_t(t) {}
T Get() { return m_t; }
Object& Deform(){
m_t*=nValue;
return *this;
}
};
template <typename T>
Object<T,0>& Object<T,0>::Deform(){
this->m_t = -1;
return *this;
}
int main(){
Object<int,7> nObj(1);
nObj.Deform();
std::cout<<nObj.Get();
}
I tried with nonmember functions and that's worked fine. What also works fine is full specialization of a member function.
我尝试使用非成员函数,效果很好。也可以正常工作的是成员函数的完全专业化。
But, whenever I try with partial spec. of a member function I get error of the form:
但是,每当我尝试使用部分规范时。的成员函数我得到形式的错误:
PartialSpecification_MemberFu.cpp(17): error: template argument
list must match the parameter list Object<T,0>& Object<T,0>::Deform().
Would appreciate any help :-)
将不胜感激任何帮助:-)
回答by Yuushi
You cannot partially specialize only a single member function, you must partially specialize the whole class. Hence you'll need something like:
您不能仅部分特化单个成员函数,您必须部分特化整个类。因此,您将需要类似的东西:
template <typename T>
class Object<T, 0>
{
private:
T m_t;
Object();
public:
Object(T t): m_t(t) {}
T Get() { return m_t; }
Object& Deform()
{
std::cout << "Spec\n";
m_t = -1;
return *this;
}
};
回答by Red XIII
14.5.5.3.1. The template parameter list of a member of a class template partial specialization shall match the template parameter list of the class template partial specialization. The template argument list of a member of a class template partial specialization shall match the template argument list of the class template partial specialization.
14.5.5.3.1。类模板部分特化成员的模板参数列表应与类模板部分特化的模板参数列表相匹配。类模板部分特化成员的模板实参列表应与类模板部分特化的模板实参列表相匹配。
In other words: no partially specialized member without partially specialized class.
换句话说:没有部分专业化的类就没有部分专业化的成员。
回答by Maksym Ganenko
Unfortunately, you can't partially specialize member function of a template class. You may either partially specialize the whole class or use inheritance. You may also use both:
不幸的是,您不能部分特化模板类的成员函数。您可以部分专门化整个类或使用继承。你也可以同时使用:
template <typename T, int nValue>
class Object {
protected:
T m_t;
public:
Object() = delete;
Object(T t): m_t(t) {}
T Get() { return m_t; }
Object& Deform() {
m_t *= nValue;
return *this;
}
};
template <typename T>
class Object<T,0> : public Object<T,1> {
public:
using Object<T,1>::Object;
Object& Deform() {
this->m_t = -1;
return *this;
}
};