Type traits doesn't work

This:

cout << std::is_const<const int*>::value; 

prints out false and I'd think that it should print true. Why does it print false?

Upvotes: 1

Views: 190

Answers (3)

Stack Overflow is garbage
Stack Overflow is garbage

Reputation: 248059

As others have mentioned, what you have is a non-const pointer to a const int. You are asking if the pointer is const, and it isn't, it can be changed. It just points to something which is const. If you want to know if the pointed-to type is const, something like this should work:

std::is_const<std::iterator_traits<const int*>::value_type>::value; 

Upvotes: 1

Potatoswatter
Potatoswatter

Reputation: 137850

Because const int * is a variable pointer to a constant integer.

std::is_const< int * const >::value is true because the type is a constant pointer to a variable integer. The const binds to whatever precedes it, unless it is first in the type specifier. I avoid putting it first to avoid invoking this "special rule."

Constant pointers are usually represented by references in C++.

To get information about the type pointed to, use std::remove_pointer.

std::is_const< typename std::remove_pointer< const int * >::type >::value

is true.

Upvotes: 9

a1ex07
a1ex07

Reputation: 37364

Because pointer to constant is not constant. You probably wanted cout << std::is_const<int *const>::value; (constant pointer to int)

Upvotes: 1

Related Questions