Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using type alias doesn't work with "const" pointer

Here, const pointer hold the address of const variable. like :

#include <iostream>

int main() 
{    
    const int i = 5;
    const int* ptr = &i;
}

It's working fine.

But, If I use using (Type alias) like:

#include <iostream>

using intptr = int*;

int main() {    
    const int i = 5;
    const intptr ptr = &i;
}

GCC compiler gives an error. [Live demo]

Why pointer does not work with using Type alias?

like image 908
msc Avatar asked Nov 13 '17 09:11

msc


2 Answers

const intptr ptr is an equivalent of int * const ptr - const pointer to non-const int, not const int * ptr - non-const pointer to const int.

If you find such right-to-left reading order for pointer declarations confusing you can utilize Straight declarations library which supplies alias templates to declare pointer types with left-to-right reading order:

const ptr<int> p; // const pointer to non-const int
ptr<const int> p; // non-const pointer to const int
like image 137
user7860670 Avatar answered Oct 14 '22 06:10

user7860670


Note that for const intptr, const is a top-level qualifier on intptr. So const is qualified on the pointer itself, then const intptr means int* const (i.e. const pointer to non-const int), not const int* (i.e. non-const pointer to const int).

like image 23
songyuanyao Avatar answered Oct 14 '22 06:10

songyuanyao