ベクターを使用して内部的に実装されたテンプレート化された Stack クラスがあります。
これが私の(簡略化された)TStack.hの内容です:
#include <vector>
#include <iostream>
template<typename T> class TStack;
template<typename T> TStack<T> operator+(const TStack<T> &s1, const TStack<T> &s2);
template<typename T>
class TStack {
friend TStack<T> operator+<>(const TStack<T> &s1, const TStack<T> &s2);
private:
std::vector<T> items;
public:
void printAll() {
std::cout << "The content of the stack is: ";
typename std::vector<T>::iterator it;
for(it = items.begin(); it < items.end(); it++) {
std::cout << *it << " ";
}
std::cout << std::endl;
}
};
template<typename T>
TStack<T> operator+(const TStack<T> &s1, const TStack<T> &s2) {
TStack<T> result = s1;
typename std::vector<T>::iterator it;
//below is line 41
for(it = s2.items.begin(); it < s2.items.end(); it++) {
result.items.push_back(*it);
}
return result;
}
そして、これは私の(簡略化された)メインクラスです:
#include <iostream>
#include "TStack.h"
using namespace std;
int main(int argc, char *argv[]) {
TStack<int> intStack;
intStack.push(4);
TStack<int> secondIntStack;
secondIntStack.push(10);
cout << "Addition result: " << endl;
//below is line 27
TStack<int> result = intStack + secondIntStack;
result.printAll();
return 0;
}
そして、これはコンパイル結果です:
In file included from main.cpp:2:
TStack.h: In function ‘TStack<T> operator+(const TStack<T>&, const TStack<T>&) [with T = int]’:
main.cpp:27: instantiated from here
TStack.h:41: error: no match for ‘operator=’ in ‘it = s2->TStack<int>::items.std::vector<_Tp, _Alloc>::begin [with _Tp = int, _Alloc = std::allocator<int>]()’
/usr/include/c++/4.4/bits/stl_iterator.h:669: note: candidates are: __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >& __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >::operator=(const __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >&)
make: *** [main.exe] Error 1
エラーメッセージの意味がわかりません。
operator+ 関数では、同じ方法で printAll() 内の反復子を取得しましたが、operator+ 関数内では正しく動作しません。operator+ 関数でイテレータを使用しないようにできることはわかっていますが、これを修正する方法に興味があります。