Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

Return type of template method in C++

I have these two header files, List.h and ListTraits.h List.h inherits from ListTraits.h, and it is meant to be a template class implementation

of std::list. Now it all works fine but the insert() method implementation. I am obliged to use ListTraits.h, in List.h, and while the std::list insert method returns

an iterator, the ListTraits.h method signature for insert is strange. These are the classes:

List.h

template <typename T> 
class List: public ListTraits<T> {
protected:
    std::list<T> list;
public:
    unsigned int size() {return 0;}

    ListTraits<T>& insert(const T& item) {     //<----------I think I should be returning iterator, but I have to return something of ListTraits<T> and that doesnt make sense
        typename std::list<T>::iterator it;
        list.insert(list.end(),  item);
        return it;
    }
    const T* getCurrentElement() const {
    
    }
    ...

And ListTraits.h

    #pragma once

//------------ Declarations for List traits used in Test1 in main.cpp
template <typename T> class ListTraits
{
    public:
        virtual unsigned int size() = 0;
        virtual ListTraits& insert(const T& item) = 0; //<-----------------------INSERT METHOD HERE---#######
        virtual void print() = 0;
};

//------------ Declarations for List traits used in Test2 in main.cpp
template <typename T> class ListTraitsExtended
{
    public:
        virtual const T* getCurrentElement() const = 0;
        virtual void advance() = 0;
        virtual void rewind() = 0;
};

Could you please help me complete the insert method so it is a templated version of the standard's libary list.insert(it, value) method?

question from:https://stackoverflow.com/questions/65941433/return-type-of-template-method-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Change

  return it;
}

to

  return *this;
}

this permits a technique known as "method chaining".

list.insert(a).insert(b).insert(c);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...