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:
value_type
?value_type
be used?For example: Point<int>::value_type
?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With