"C++ Common Knowledge" Item 53 - Template Question

Hi,

I'm having trouble following Item 53 in Stephen Dewhurst's book C++ Common Knowledge. It's hard to put the point I'm stuck on in context here without reproducing a lot from the book - so maybe someone with access to the book could help me out with explaining what is going on in the first statement in the Template function given in the following code snippet from Item 53:

1
2
3
4
5
6
7
template <class Container>
typename Container::Elem process( Container &c, int size ) {
    typename Container::Temp temp = typename Container::Elem();
    for ( int i = 0; i < size; ++i )
        temp += c[i];
    return temp;
}


I understand all three uses of the typename keyword in the code snippet and the Container::Elem function return type - my confusion lies in what the first statement (directly before the for loop) is doing and in particular what does Elem() mean?
Elem() is a constructor for Container::Elem. What that statement does is initializes a Container::Temp named temp using Container::Elem's constructor (maybe Temp is derived from Elem?).

EDIT: Fixed some grammar errors.

-Albatross
Last edited on
Thanks for the reply.

Maybe I was a little ahead of myself then when I said I understood the three uses of the typename keyword in the code snippet I quoted!

I didn't realise the typename keyword could be used like this when calling a constructor.

So now I'm still confused but on a different point. In the only example code for a container in the chapter (Item 53) in the book we see:

1
2
3
4
5
6
7
8
template <class T>
class Seq {
  public:
    typedef T Elem;
    typedef T Temp;
    size_t size() const;
    //...
};


and earlier the text reads: "In the process generic algorithm, we need to know the element type (Elem) of Container, as well as a type that could serve to declare a temporary for holding objects of the element type (Temp), but that information is not available until the process function template is instantiated with a specific container."

BTW the "process generic algorithm" is the template function in the code I quoted in my original post on this topic above.

If the suggestion is that Elem and Temp in the example are both typedefs for the same type, why the need for the two typedefs? Also why does the first statement in the template function which I quoted in my original post not simply read:

typename Container::Elem temp;

?

Obviously since both Elem and Temp are aliases of the same type, one of them
is redundant.

Q2: In the case where Container::Elem is a POD type, say an int, your line of
code does not initialize the int to any particular value, whereas the original
code will ensure it is initialized to zero.
In my understood,
typename Container::Elem
declares that Elem is a type in Container, it called "dependent type". Just like
string::size_type.
Last edited on
Thanks.
Topic archived. No new replies allowed.