typedef

Included in a class template def, what is the typedef line for?

...

template <typename T>
class TVector
{
public:
// scope TVector<T>:: type definitions
typedef T ValueType;

...
It is common practice to "save off" the templated type T as a typedef inside the class. All STL containers do it, although they use the symbol "value_type" as opposed to the mixed case. It is useful for metaprogramming.

Thanks for the reply, jsmith, but I don't quite get what you mean. Could you explain it a different way - my brain is kind of sluggish today (and probably most other days...)
Consider iter_swap:

iter_swap takes two iterators and swaps the values that are referenced by the iterators. ie, much like std::swap.

The swap algorithm is well-known: make a temporary copy of one value; copy the second to the first, copy the temporary to the second.

In order to be able to do this, however, one has to know the type that the iterator refers to (to instantiate the temporary).

Because all iterator classes in STL have a value_type typedef which stores the contained type, this is possible. Without this typedef, it is much, much harder to declare iter_swap.

1
2
3
4
5
6
7
8
9
10
11
12
13
// From stl_algobase.h:
//    Some extraneous stuff removed for brevity:
  template<typename _ForwardIter1, typename _ForwardIter2>
    inline void
    iter_swap(_ForwardIter1 __a, _ForwardIter2 __b)
    {
      typedef typename iterator_traits<_ForwardIter1>::value_type _ValueType1;
      typedef typename iterator_traits<_ForwardIter2>::value_type _ValueType2;
 
      _ValueType1 __tmp = *__a;
      *__a = *__b;
      *__b = __tmp;
    }
Topic archived. No new replies allowed.