Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare const pointer to int?

In C++ we have the following:

int* p1;              // pointer to int
const int* p2;        // pointer to constant int
int* const p3;        // constant pointer to int
const int* const p4;  // constant pointer to constant int

and in D:

int* p1;              // pointer to int
const(int)* p2;       // pointer to constant int
?? ?? ??              // constant pointer to int
const(int*) p4;       // constant pointer to constant int

what's the syntax for constant pointer to int?

like image 551
Arlen Avatar asked Dec 14 '11 00:12

Arlen


2 Answers

D does not have head const.

like image 83
Vladimir Panteleev Avatar answered Sep 29 '22 02:09

Vladimir Panteleev


I think you can simulate it:

struct Ptr(T)
{
    T* _val;

    this(T* nval) const
    {
        _val = nval;
    }

    @property T* opCall() const
    {
        return cast(T*)_val;
    }

    alias opCall this;
}

void main()
{
    int x = 1;
    int y = 2;
    const Ptr!int ptrInt = &x;
    assert(*ptrInt == 1);

    *ptrInt = y;  // ok
    assert(*ptrInt == 2);
    assert(x == 2);

    ptrInt = &y;  // won't compile, good.
}
like image 41
Andrej Mitrović Avatar answered Sep 29 '22 02:09

Andrej Mitrović