How to define a template class that gives the depth / level of a type pointer?

How can I define a template class that provides an integer constant representing the "depth" of the type (pointer) provided as an argument to the input template? For example, if a class was called by Depth , the following would be true:

 Depth<int ***>::value == 3 Depth<int>::value == 0 
+7
source share
2 answers
 template <typename T> struct pointer_depth_impl { enum { value = 0 }; }; template <typename T> struct pointer_depth_impl<T* const volatile> { enum { value = pointer_depth_impl<T const volatile>::value + 1 }; }; template <typename T> struct pointer_depth { enum { value = pointer_depth_impl<T const volatile>::value }; }; 
+14
source

This can be done through recursion.

 template<typename T> struct Depth { enum { value = 0 }; }; template<typename T> struct Depth<T*> { enum { value = Depth<T>::value + 1 }; }; 
+4
source

All Articles