开发者

C++ Qualification conversions - constness and templates

In the code below, I'm trying to figure out why the compiler (msdev c++ 2010 and Comeau) does not consider the return type of the non specialized template get function to be const. I would expect CASE #2 (see code snipet) to NOT compile, yet it does. Any ideas or links?

Thank you, regu

template < typename T >
struct constness
{
  T value;
  constness() : value(0) {}
  const T &get() { return value; }
};

template < typename T >
struct constness< T * >
{
   T * const value;开发者_如何学Go
   constness() : value(0) {}
   const T * const &get() { return value; }
};

int main( int argc, const char* argv[] )
{
  // Uses specialized
  constness< double * > wConstness;
  const_cast< double * & >(wConstness.value) = new double(1);
  *wConstness.get() = 12.0; // CASE #1 doesn't compile

  // Uses non specialized 
  constness< double * const > wConstness2;
  const_cast< double * & >(wConstness2.value) = new double(1);
  *wConstness2.get() = 12.0; // CASE #2 compiles, allowing modification of 
                             // value pointed by wConstness2.value

  return 0;
};


You instantiate constness with T = double * const (a const-qualified pointer to a non-const-qualified double).

In const T& get(), the const applies to the whole T. If T was int*, then const T would be int* const, not const int*. So in your specific case, the const has no effect because T is already const-qualified (it is a double* const).

When you have a typename like T, adding const or volatile to the typename always applies at the top level regardless of what the type is. So, const T and T const are always the same, regardless what T is.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜