2011-05-25 60 views
1
#include <iostream> 
#include <map> 
#include <vector> 


template<typename T> 
class foo { 
    public: 
     foo(T val) : m_Value(val) { }; 
     T get_value() const { return m_Value; }; 
     void set_value(const T& t) { m_Value=t; }; 
     bool operator<(const foo<T>& x) { return x.get_value() < m_Value; }; 
     bool operator==(const foo<T>& x) { return x.get_value() == m_Value; }; 
    private: 
     T m_Value; 
}; 

template<typename T> 
class bar { 
    public: 
     bar() { }; 
     void print_first() const { 
      typename std::map<foo<T>,std::vector<foo<T> > >::iterator it; 
      it = m_Map.begin(); //ERROR! 
      std::cout << it->first.get_value() << std::endl; 
     }; 
    private: 
     std::map<foo<T>,std::vector<foo<T> > > m_Map; 
}; 

int main() { 
    bar<int> b; 
    b.print_first(); 
    return 0; 
}; 

我想寫一個容器,但成員函數需要使用一個迭代的,但是當我嘗試實際使用迭代器,我得到一個錯誤:這個模板代碼有什麼問題?

testcase.cpp: In member function `void bar<T>::print_first() const [with T = 
    int]': 
testcase.cpp:33: instantiated from here 
testcase.cpp:24: error: no match for 'operator=' in 'it = std::map<_Key, _Tp, 
    _Compare, _Alloc>::begin() const [with _Key = foo<int>, _Tp = 
    std::vector<foo<int>, std::allocator<foo<int> > >, _Compare = 
    std::less<foo<int> >, _Alloc = std::allocator<std::pair<const foo<int>, 
    std::vector<foo<int>, std::allocator<foo<int> > > > >]()' 
/usr/include/c++/3.3.3/bits/stl_tree.h:184: error: candidates are: 
    std::_Rb_tree_iterator<std::pair<const foo<int>, std::vector<foo<int>, 
    std::allocator<foo<int> > > >, std::pair<const foo<int>, 
    std::vector<foo<int>, std::allocator<foo<int> > > >&, std::pair<const 
    foo<int>, std::vector<foo<int>, std::allocator<foo<int> > > >*>& 
    std::_Rb_tree_iterator<std::pair<const foo<int>, std::vector<foo<int>, 
    std::allocator<foo<int> > > >, std::pair<const foo<int>, 
    std::vector<foo<int>, std::allocator<foo<int> > > >&, std::pair<const 
    foo<int>, std::vector<foo<int>, std::allocator<foo<int> > > 
    >*>::operator=(const std::_Rb_tree_iterator<std::pair<const foo<int>, 
    std::vector<foo<int>, std::allocator<foo<int> > > >, std::pair<const 
    foo<int>, std::vector<foo<int>, std::allocator<foo<int> > > >&, 
    std::pair<const foo<int>, std::vector<foo<int>, std::allocator<foo<int> > > 
    >*>&) 

它是什麼,我做錯了嗎? 在此先感謝。

回答

9

print_firstconst方法。因此,成員m_Map也是const,其begin方法不會返回普通的iterator,而是返回const_iterator。更改

typename std::map<foo<T>,std::vector<foo<T> > >::iterator it; 

typename std::map<foo<T>,std::vector<foo<T> > >::const_iterator it; 

,你應該是好去。

+0

良好的調用我錯過了該方法的'const'關鍵字。對於記錄來說,在處理模板代碼時,我仍然會充分使用'typedef'或'auto'來提高可讀性。 – AJG85 2011-05-25 23:57:15