我試圖用C++模板模板參數工作,與著名的堆棧例子:C++模板的模板:不能訪問私有成員
不過,我在下面的代碼得到acompilation錯誤。我的理解是,和'Stack<T, CONT>'
是相同的類,所以'容器'在'Stack<T, CONT>::operator = (const Stack<T2, CONT2>& rhs)'
可以幫助我嗎?在使用模板模板參數時,有什麼特別的地方需要注意嗎?
template <typename T,
template < typename ELEM, typename ALLOC = std::allocator<ELEM> > class CONT = std::deque >
class Stack
{
CONT<T> container ;
public :
Stack() {} ;
template <typename T2>
void push_back (const T2& elem) ;
bool isEmpty (void) const ;
template <typename T2,
template < typename ELEM2, typename = std::allocator<ELEM2> > class CONT2 >
Stack<T, CONT>& operator = (const Stack<T2,CONT2>& rhs) ;
void push_back (T const& elem) {
container.push_back (elem) ;
};
T operator [] (size_t i) const ;
T& operator [] (size_t i) ;
};
template <typename T, template <typename ELEM, typename ALLOC > class CONT >
T Stack<T, CONT>::operator [] (size_t i) const {
return container [i] ;
}
template <typename T, template <typename ELEM, typename ALLOC > class CONT >
T& Stack<T, CONT>::operator[] (size_t i)
{
return container [i] ;
}
template <typename T, template <typename ELEM, typename ALLOC > class CONT >
template <typename T2, template < typename , typename > class CONT2 >
Stack<T, CONT>& Stack<T, CONT>::operator = (const Stack<T2, CONT2>& rhs)
{
if (this->container != rhs.container) // ERROR !!!
{
if (this->container.size() == 0)
{
for (size_t i = 0 ; i < rhs.container.size() ; ++i)
{
(*this).container.push_back((T) rhs[i]) ;
}
}
else
{
for (size_t i = 0 ; i < this->container.size() ; ++i)
{
(*this)[i] = rhs[i] ;
}
}
}
return *this ;
}
int main()
{
Stack<int> stk ;
Stack<double> stkd ;
stk.push_back(10) ;
stk.push_back(5) ;
stkd = stk ;
int st = stk[1] ;
return 0;
}
的編譯錯誤是:
>e:\project2\project2\source.cpp(46): error C2248: 'Stack<T>::container' : cannot access private member declared in class 'Stack<T>'
1> with
1> [
1> T=int
1> ]
1> e:\project2\project2\source.cpp(12) : see declaration of 'Stack<T>::container'
1> with
1> [
1> T=int
1> ]
1> e:\project2\project2\source.cpp(75) : see reference to function template instantiation 'Stack<T> &Stack<T>::operator =<int,std::deque>(const Stack<int> &)' being compiled
1> with
1> [
1> T=double
1> ]
1> e:\project2\project2\source.cpp(75) : see reference to function template instantiation 'Stack<T> &Stack<T>::operator =<int,std::deque>(const Stack<int> &)' being compiled
1> with
1> [
1> T=double
1> ]
不,'棧'和'堆棧'ARA不同的類。 –
songyuanyao
堆棧不是一個開始的類。這是一個類模板。 –
加上:模板朋友類堆棧;' –
user5821508