Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare n-th order pointers in runtime in C++

Pointers can be declared like this:

int
    a = 1,
    *b = &a,      // 1st order pointer
    **c = &b,     // 2nd order pointer
    ***d = &c,    // 3rd order pointer
    ****e = &d,   // 4th order pointer
    *****f = &e,  // 5th order pointer
    *** n-stars *** f;  // n-th order pointer

Here, we need to know at compile-time the order of the pointer when we are declaring it. Is it possible at all to declare a pointer, whose order is only known at run time? Linked to this question is whether is it possible to query at run-time the order of an arbitrary pointer?

int order = GET_ORDER_OF_PTR(f) // returns 5
int /* insert some syntax here to make ptr a pointer of order (order + 1) */ ptr = &f;

Note: I already know this (generally) might not be a good idea. Still want to know if it's doable :)

like image 241
ButterDog Avatar asked Dec 14 '22 20:12

ButterDog


1 Answers

In runtime you cannot - because C++ is statically typed. During compilation it is possible with templates, e.g.

template<typename T, int order> struct P
{
  typedef typename P<T, order-1>::pointer* pointer;
};

template<typename T> struct P<T, 0>
{
  typedef T pointer;
};

Then P<int, 3>::pointer is equivalent to int***.

like image 145
Wojtek Surowka Avatar answered Dec 29 '22 06:12

Wojtek Surowka