Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

template<typename T>
class Point
{
public:
    typedef T value_type;
    ...
};

I have seen the above code in the book "C++ in a Nutshell" by Ray Lischner, pp176.

Questions:

  1. Is it a good practice to always add the definition for value_type?
  2. Where will this defined value_type be used?

For example: Point<int>::value_type?

like image 497
q0987 Avatar asked Mar 09 '12 15:03

q0987


2 Answers

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.

like image 69
Xeo Avatar answered Oct 14 '22 02:10

Xeo


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;
 }
like image 9
eduffy Avatar answered Oct 14 '22 02:10

eduffy