Templates and STL

前端 未结 6 1772
情歌与酒
情歌与酒 2021-01-05 18:31

The following code represents a container based on std::vector

template 
struct TList
{
    typedef std::vector  Type;
};


         


        
6条回答
  •  感情败类
    2021-01-05 18:51

    I'm a bit puzzled why some very smart (and competent) people are saying no.

    Unless I've misread your question, what you're trying to accomplish is virtually identical to the "container adapters" in the standard library. Each provides an interface to some underlying container type, with the container type that will be used provided as a template parameter (with a default value).

    For example, a std::stack uses some other container (e.g., std::deque, std::list or std::vector) to hold the objects, and std::stack itself just provides a simplified/restricted interface for when you just want to use stack operations. The underlying container that will be used by the std::stack is provided as a template parameter. Here's how the code looks in the standard:

    namespace std {
        template  >
        class stack {
        public:
            typedef typename Container::value_type value_type;
            typedef typename Container::size_type  size_type;
            typedef Container                      container_type;
        protected:
            Container c;
        public:
            explicit stack(const Container& = Container());
            bool empty() const             { return c.empty(); }
            size_type size() const         { return c.size(); }
            value_type& top()              { return c.back(); }
            const value_type& top() const  { return c.back(); }
            void push(const value_type& x) { c.push_back(x); }
            void pop()                     { c.pop_back(); }
        };
    }
    

    Of course, perhaps I've just misunderstood the question -- if so, I apologize in advance to the people with whom I'm (sort of) disagreeing.

提交回复
热议问题