Is there a "general" type of iterator that will be used in C ++ for function parameters?

I have a C ++ class that contains a member std::list. Now I want to add a method that can be used to insert the values ​​of another container into this list. Something like that:

template<class factType>
class BeliefSet
{
    std::list<factType> m_List;
    void SetFacts(??? IterBegin, ??? IterEnd)
    {
        m_List.insert(m_List.end(), IterBegin, IterEnd);
    }
};

Now my question is: what do I need to replace ???, so that it can take an iterator of any (or at least the most common) containers std, such as list, vectoretc ...? I tried it with help std::iterator<std::input_iterator_tag, factType>, but that didn't work.

Note that this should also work with the copy constructor, for example:

const std::list<factType>& GetFacts() const
{
    return m_List;
}

// Copy constructor.
explicit BeliefSet(const BeliefSet& Other)
{
    auto facts = Other.GetFacts();
    SetFacts(facts.begin(), facts.end());
}
+4
source share
3 answers

SetFacts . , , . , BeliefSet , .

template<class factType>
class BeliefSet
{
    std::list<factType> m_List;

    template <class It>
    void SetFacts(It IterBegin, It IterEnd)
    {
        m_List.insert(m_List.end(), IterBegin, IterEnd);
    }
};

SetFacts -, , list::insert. , !

, ( ) - , , .

+5

iterator_tag.

template<class factType>
class BeliefSet
{

    std::list<factType> m_List;
    template <typename Iter>
    void SetFacts(Iter IterBegin, Iter IterEnd)
    {
        SetFacts_Impl(IterBegin, IterEnd, 
         typename std::iterator_traits<Iter>::iterator_category());
    }
private:
    template <typename Iter>
    void SetFacts_Impl(Iter IterBegin, Iter IterEnd, std:: bidirectional_iterator_tag )
    {
        std::copy( IterBegin, IterEnd, std::back_inserter( m_List ) );
    }
};

, , , bidirectional iterator. list, vector

+2
template <class Iter>
void SetFacts(Iter first, Iter last)
    {
        m_List.insert(m_List.end(), first, last);
    }

.

+2

Source: https://habr.com/ru/post/1663342/


All Articles