How can I define a template class which provides an integer constant representing the "depth" of a (pointer) type provided as the input template argument? For example, if the class was called Depth
, the following would be true:
Depth<int ***>::value == 3
Depth<int>::value == 0
There are ways to restrict the types you can use inside a template you write by using specific typedefs inside your template. This will ensure that the compilation of the template specialisation for a type that does not include that particular typedef will fail, so you can selectively support/not support certain types.
A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.
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 };
};
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