samedi 3 décembre 2016

Can't pass iterator to a class method in C++

I have the following simple class:

template <class T> class ListWrap
{
    std::list<T> m_List;
    explicit ListWrap(std::initializer_list<T> data)
    {
        Set(data);
    }
    void Set(std::initializer_list<T> data)
    {
        m_List.clear();
        m_List.insert(m_List.end(), data);
    }
};

This works fine, I can instantiate a new object ListWrap using an initializer list. Now I also want to allow to set m_List from another list or iterator, and to use that from a copy constructor.

So I tried to add the following:

// copy constructor
explicit ListWrap(const ListWrap& Other)
{
    Set(Other.m_List.begin());
}
void Set(std::iterator<std::list<T>, T> Iterator)
{
    m_List.clear();
    m_List.insert(m_List.end(), Iterator);
}

However, now when I try to compile I get the following error:

error C2664: cannot convert argument 1 from
   'std::_List_const_iterator<std::_List_val<std::_List_simple_types<int>>>'
to 'std::initializer_list<_Ty>'*

This error message refers to the call to Set() in the new copy constructor. So it seems it tries to use the "old" Set() method with the initializer list instead of the second, "new" version of Set() that receives an iterator.

Any ideas what I am missing here?

Aucun commentaire:

Enregistrer un commentaire