简体   繁体   English

模板类成员函数只有特化

[英]template class member function only specialization

I am reading the Complete Guide on Templates and it says the following:我正在阅读关于模板的完整指南,它说明了以下内容:

Where it is talking about class template specialization.它在哪里谈论类模板专业化。

Although it is possible to specialize a single member function of a class template, once you have done so, you can no longer specialize the whole class template instance that the specialized member belongs to.尽管可以特化类模板的单个成员函数,但是一旦这样做,就不能再特化该特化成员所属的整个类模板实例。

I'm actually wondering how this is true, cause you can specialize without any member functions at all.我实际上想知道这是怎么回事,因为您可以在没有任何成员函数的情况下进行专业化。 Is it saying that you cannot have a specialization with only one member function and then another with all member functions?是不是说你不能有一个只有一个成员函数的专业化,然后另一个有所有成员函数的专业化?

Can someone please clarify?有人可以澄清吗?

I think it is referring to the following case:我认为它指的是以下案例:

template <typename T>
struct base {
   void foo() { std::cout << "generic" << std::endl; }
   void bar() { std::cout << "bar" << std::endl; }
};
template <>
void base<int>::foo() // specialize only one member
{ 
   std::cout << "int" << std::endl; 
}
int main() {
   base<int> i;
   i.foo();         // int
   i.bar();         // bar
}

Once that is done, you cannot specialize the full template to be any other thing, so一旦完成,您就不能将完整模板特化为任何其他东西,因此

template <>
struct base<int> {};  // error

I think what is meant is that you can either:我认为这意味着您可以:

  • specialize the whole class and all members (data and functions, static or not, virtual or not) have to be declared and defined even if they are the same as for the non specialized version,特化整个类,所有成员(数据和函数,静态与否,虚拟与否)必须声明和定义,即使它们与非专用版本相同,

  • specialize some function members, but then you can't specialize the whole class (ie all members are declared in the same way as for the non specialized case, you just provide the implementation for some function members).特化一些函数成员,但是你不能特化整个类(即所有成员的声明方式与非特化情况相同,您只需提供一些函数成员的实现)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM