jbcoe
jbcoe

Reputation: 3921

std::is_const identifies const pointer as non-const

I am puzzled by std::is_const's behaviour in identifying a const pointer as non-const. My own implementation of is_const does exactly the same thing. I'm not sure why the more general templated struct <T>is being picked over the <const T> version. Both gcc4.7 and clang3.1-svn show the same behaviour. Can anyone explain what's going on? Code is given 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 instances is_const<const CEmptyClass*>::value returns 0

Upvotes: 7

Views: 1274

Answers (1)

K-ballo
K-ballo

Reputation: 81349

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

int& const i;

Now if you were to remove your reference, it would work. If you were to place const on the right side (semantically is the same thing), and read the type backwards

CEmptyClass const&

it would read a reference to a const CEmptyClass, not a const reference to an CEmptyClass.

Update: Now that you changed the reference to a pointer, the same misconstruction persist:

const CEmptyClass*
CEmptyClass const*

both are the same, a non-const pointer to a const CEmptyClass

CEmptyClass* const

is a const pointer to a CEmptyClass

and

const CEmptyClass* const
CEmptyClass const* const

are a const pointer to a const CEmptyClass.

Upvotes: 19

Related Questions