Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I define a template class which gives the pointer depth/level of a type?

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
like image 523
user2023370 Avatar asked Apr 02 '11 01:04

user2023370


People also ask

How will you restrict the template for a specific datatype?

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.

What can the template parameter in C++ template definition be?

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.


1 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 };
};
like image 102
James McNellis Avatar answered Sep 20 '22 07:09

James McNellis