Is it a good practice to always define `value_type` when we define a template

It doesn't hurt to have one, but it mostly only makes sense for containers (like std::vector), as all containers provide this typedef and a uniform interface for accessing the contained values (begin/end, front/back), although this has mostly gotten obsolete in C++11 with auto and decltype. It's still cleaner to say some_template<typename container::value_type> ..., though.

That in turn means they can be used interchangeably in generic code (the main reason why things were done that way). If it makes sense for your Point class to know what types the contained values are, well, have that typedef. As I said, it doesn't hurt. However, I have a feeling that it doesn't make too much sense for that particular example.


It's good practice for writing functions that perform on containers. For example, if I wrote a swap function that accepts a container (templated), and two indices to swap, then I could use the value_type definition to define a temp variable.

 template<typename T>
 void swap(T &container, int i, int j) {
    typename T::value_type temp = container[i];
    container[i] = container[j];
    container[i] = temp;
 }

Tags:

C++