Question

Which type can 0 be cast to? pointers, numeric vars. Any others? Will the following cast be safe?

ps: an excerpt from STL implementation of iterator

template <class Iterator>
inline typename iterator_traits<Iterator>::difference_type*
distance_type(const Iterator&) {
  return static_cast<typename iterator_traits<Iterator>::difference_type*>(0);
}

template <class Iterator>
inline typename iterator_traits<Iterator>::value_type*
value_type(const Iterator&) {
  return static_cast<typename iterator_traits<Iterator>::value_type*>(0);
}
Was it helpful?

Solution

All kinds of pointers including pointer-to-function, pointer-to-member, pointer-to-member-function; arithmetic types; anything with a 1-arg int constructor; anything with a 1-arg constructor taking a type that 0 can be implicitly converted to. Probably something else I haven't thought of.

Assuming that iterator_traits resolves to std::iterator_traits, then typename iterator_traits<Iterator>::difference_type* is certainly a pointer-to-object type, except perhaps in a program that has an incorrect specialization of iterator_traits. So yes, the cast works.

If you messed up and defined difference_type or value_type as a reference type, or not a type at all, then you'd have problems with that code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top