dkmg
dkmg

Reputation: 17

C++ Iterator declare from typedef std::map as template argument

How can I declare an iterator for template argument map?

I know I could pass it as argument from main function as another template argument, but if I don't, how can I declare it?

template< typename container >
int print_data( container map )
{
    map::iterator iter; // this is wrong
    return 0;
}

int main()
{
    typedef std::map< int, double > Map;
    Map new_map;

    print_data< Map >( new_map );
}

Upvotes: 0

Views: 827

Answers (3)

SoronelHaetir
SoronelHaetir

Reputation: 15164

typename Container::iterator iter = ...;

The compiler defaults to seeing template members as variables, if it's a type you have to say so with "typename".

Upvotes: 0

R Sahu
R Sahu

Reputation: 206567

If you are able to use a C++11 (or later) compiler, you have couple of more ways to declare iter.

  1. If you can declare and initialize it in one statement, you can use:

    auto iter = map.begin();
    
  2. You can also use decltype to deduce the type.

    using iterator_type = decltype(map.begin());
    iterator_type iter;
    

I would recommend using the first method. It is less code to deal with. It's also a better programming habit to declare and initialize a variable in one statement.

Upvotes: 0

While

map::iterator iter; // this is wrong

is true. That's only because you use the scope resolution operator on an object, instead of something that designates a scope, like a class name or a namespace. So this:

typename container::iterator iter;

Would be correct. Note the typename keyword is important and mandatory. You must let the compiler know this dependent name you are accessing is a type, so the line would be parsed as a declaration.

Upvotes: 2

Related Questions