mercredi 24 octobre 2018

Range based for loop on templated vector

If I write this, everything compiles and works as expected:

#include <iostream>
#include <vector>

using namespace std;

class ClassWithIntVector
{
public:

    typedef std::vector< int >::iterator iterator;

    iterator begin()
    {
        return myVector.begin();
    }
    iterator end()
    {
        return myVector.end();
    }

    void Add( int i )
    {
        myVector.push_back( i );
    }

private:
    std::vector< int > myVector;
};


int main()
{
    ClassWithIntVector IV;
    IV.Add(1);
    IV.Add(2);
    for( auto& x : IV )
        std::cout << x << " ";

    return 0;
}

However, I get compiler errors when I write

template <typename T >
class ClassWithTempVector
{
public:

    typedef std::vector< typename T >::iterator iterator;

 ...

||=== Build: Debug in test (compiler: GNU GCC Compiler) ===|
C:\Users\James\code\test\main.cpp|35|error: template argument 1 is invalid|
C:\Users\James\code\test\main.cpp|35|error: template argument 2 is invalid|
C:\Users\James\code\test\main.cpp|35|error: typedef name may not be a nested-name-specifier|

How do I persuade the compiler to accept my templated class?

Aucun commentaire:

Enregistrer un commentaire