C++ 模板完整指南。赋值运算符

C++ Templates the complete guide. Assign operator

作为本书中的示例:http://www.amazon.com/C-Templates-The-Complete-Guide/dp/0201734842 他们有这个 class:

template <typename T> 
class Stack { 
 private: 
 std::deque<T> elems; // elements
 public: 
 void push(T const&); // push element
 void pop(); // pop element
 T top() const; // return top element
 bool empty() const { // return whether the stack is empty
 return elems.empty(); 
 } 
 // assign stack of elements of type T2 
 template <typename T2> 
 Stack<T>& operator= (Stack<T2> const&); 
}; 

下面是赋值运算符的实现:

template <typename T> 
 template <typename T2> 
Stack<T>& Stack<T>::operator= (Stack<T2> const& op2) 
{ 
 if ((void*)this == (void*)&op2) { // assignment to itself?
 return *this; 
 } 
 Stack<T2> tmp(op2); // create a copy of the assigned stack
 elems.clear(); // remove existing elements
 while (!tmp.empty()) { // copy all elements
 elems.push_front(tmp.top()); 
 tmp.pop(); 
 } 
 return *this; 
} 

下面是对该方法的作用的一些解释:

Inside the member function you may expect simply to access all necessary data for the assigned stack op2. However, this stack has a different type (if you instantiate a class template for two different types, you get two different types), so you are restricted to using the public interface. It follows that the only way to access the elements is by calling top(). However, each element has to become a top element, then. Thus, a copy of op2 must first be made, so that the elements are taken from that copy by calling pop().

我对这部分感到困惑:

However, this stack has a different type (if you instantiate a class template for two different types, you get two different types), so you are restricted to using the public interface.

这是说我只能使用 public 接口,还是不允许我使用 public 接口? 如果这意味着我不允许使用 public 接口,那么什么是 top() 成员函数?不就是public方法吗?

However, this stack has a different type (if you instantiate a class template for two different types, you get two different types), so you are restricted to using the public interface.

这意味着您应该只使用public接口。事实上,如果你想实现 operator= 函数,那么你 必须只使用 public 接口。

如果您不使用 public 接口,您将无法访问 top() 函数,这是将堆栈的元素分配给另一个堆栈的唯一方法.

是的,top() 是一个 public 函数

如果 T != T2

Stack<T>Stack<T2> 是不相关的类型, 所以 Stack<T> 的方法不能使用 Stack<T2> 的私有成员(除非声明为 friend)。

Stack<T>(与任何其他 类 一样)仅限于使用 Stack<T2>.

的 public 接口