【问题标题】:What is wrong with this template code?这个模板代码有什么问题?
【发布时间】:2011-05-25 23:43:47
【问题描述】:
#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> > >
   >*>&)

我做错了什么? 提前致谢。

【问题讨论】:

    标签: c++ templates iterator


    【解决方案1】:

    print_first 是一个const 方法。因此成员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;
    

    你应该很高兴。

    【讨论】:

    • 好电话我错过了方法上的const 关键字。为了记录,在处理模板代码时,我仍然会充分使用typedefauto 以使事情更具可读性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-07
    • 2014-08-29
    • 2013-06-05
    • 2014-06-04
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多