简体   繁体   中英

C++ Template Wrapper class for std::vector

I'm trying to encapsulate the C++ Standard Library's vector class using templates but I keep getting the error

SceneVector.h: In member function ‘void scenegraph::SceneVector<V>::print()’:
SceneVector.h:40: error: expected ‘;’ before ‘it’
SceneVector.h:40: error: ‘it’ was not declared in this scope

The code I've managed to create is

#include <map>
#include <vector>
#include <iostream>

namespace scenegraph
{
    template <class V> class SceneVector
    {
        typedef std::vector<V> Vector;
        Vector vector;

        public:
            SceneVector();
            void insert(const V value);
            void print();
    };

    template <class V> SceneVector<V>::SceneVector()
    {
        vector.clear();
    }

    template <class V> void SceneVector<V>::insert(const V value)
    {
        vector.push_back(value);
    }

        template <class V> void SceneVector<V>::print()
    {
        for(Vector::iterator it = vector.begin(); it != vector.end(); ++it)
        {
            std::cout << "[" << (*it) << "] " << std::endl;
        }
        std::cout << std::endl;
    }
}

Can anyone correct me here? I must reinforce I'm a C++ newbie so the answer may be extremely trivial.

When accessing types that depend on a template parameter, you must prepend typename to make clear to the parser that the type is a type.

for(typename Vector::iterator it = vector.begin(); it != vector.end(); ++it)

It is possible for Vector::iterator to be a compile-time constant number, and the compiler can't know that until instantiation time. That's why you have to tell it explicitely.

If you had a plain

std::vector<V>::iterator

it would be pretty obvious that it is dependent name, and that you need a typename to indicate that iterator is a type.

Using a typedef doesn't really change that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM