typedef – non-optional in this case

Someone asked me to write a utility function to print any STL container, in my own loop. I suggested we follow the STL convention to use iterator inputs. Echoed on http://stackoverflow.com/questions/4657767/how-to-templatize-a-function-on-an-stl-container-that-has-an-iterator. However, what if we pass the container itself as input (assuming it’s a standard-conforming container)?

void dump(const CT& cont) {
    typedef typename CT::const_iterator iterator; //no choice
    iterator i;
    //won’t compile — CT::const_iterator i;
    for(i = cont.begin();   i!= cont.end();   ++i){
        cout<<*i <<" "<<endl;

This works but the typedef isn’t sugar-coating. Without it you get

dependent-name ` M::const_iterator’ is parsed as a non-type, but instantiation yields a type

Very loosely, CT::const_iterator i suggests to the compiler to create a concrete type for i but CT::const_iterator is not a generic type, not “concretized” [1]. Solution — The typedef dresses up this “generic type” as if it’s an end-user type, usable in a variable declaration

[1] remember the Barcap FMD eval objects?


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s