Std :: is_const identifies a constant pointer as non-constant

What puzzles me is the behavior of std::is_const when defining a const pointer as non const . My own implementation of is_const does the same. I'm not sure why a more general template structure <T> is selected over the version of <const T> . Both gcc4.7 and clang3.1-svn show the same behavior. Can someone explain what is happening? The code is below:

 #include <iostream> #include <sstream> #include <type_traits> class CEmptyClass {}; namespace jbc { template <typename T> struct is_const : std::false_type {}; template <typename T> struct is_const<const T> : std::true_type {}; } int main(int argc, char* argv[]) { std::cout << "Is 'const CEmptyClass*' constant according to std lib : " << std::is_const<const CEmptyClass*>::value << std::endl; std::cout << "Is 'const CEmptyClass*' constant according to jbc : " << jbc::is_const<const CEmptyClass*>::value << std::endl; } 

In both cases, is_const<const CEmptyClass*>::value returns 0

+4
source share
1 answer

There is no such thing as a const link, a link is never const . Code like this does not compile:

 int& const i; 

Now, if you want to remove your link, this will work. If you put const on the right side (semantically the same thing) and read the type back

 CEmptyClass const& 

he would read a reference to const CEmptyClass, not a reference to CEmptyClass constant.

Update: Now that you have changed the link to the pointer, the same incorrect construction is preserved:

 const CEmptyClass* CEmptyClass const* 

both are the same, the pointer is not const for CEmptyClass constant

 CEmptyClass* const 

is a const pointer to CEmptyClass

and

 const CEmptyClass* const CEmptyClass const* const 

are const pointers to const CEmptyClass.

+17
source

Source: https://habr.com/ru/post/1415771/


All Articles