Foaly
Foaly

Reputation: 597

using vs. typedef for std::vector::iterator

I am having a problem when using the new C++11 using keyword. As far as I understand, it's an alias for typedef. But I cannot get it to compile. I want to define an alias for an iterator of a std::vector. If I use this everything works perfectly.

typedef std::vector<fix_point>::iterator inputIterator;

But if I try:

using std::vector<fix_point>::iterator = inputIterator;

The code doesn't compile with:

Error: 'std::vector<fix_point>' is not a namespace
using std::vector<fix_point>::iterator = inputIterator;
                            ^

Why doesn't this compile?

Upvotes: 4

Views: 1392

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311048

typedef is a specifier that may be mixed with other specifiers. Thus the following typedef declarations are equivalent.

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

Opposite to the typedef declaration the alias declaration has strict order of specifiers. According to the C++ Standard (7.1.3 The typedef specifier)

A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name. It has the same semantics as if it were introduced by the typedef specifier. In particular, it does not define a new type and it shall not appear in the type-id.

Thus you have to write

using inputIterator = std::vector<int>::iterator ;

Upvotes: 9

Barry
Barry

Reputation: 303337

You just have it backwards:

using inputIterator = std::vector<fix_point>::iterator;

The alias syntax sort of mirrors the variable declaration syntax: the name you're introducing goes on the left side of the =.

Upvotes: 14

Related Questions