4

Possible Duplicate:
typedef and containers of const pointers

Why is the code emitting an error?

int main()
{
  //test code
  typedef int& Ref_to_int;
  const Ref_to_int ref = 10; 
}

The error is:

error: invalid initialization of non-const reference of type ‘int&’ from a temporary of type ‘int’

I read the post on prolonging the lifetime of temporaries which says that temporaries can be bound to references to const. Then why is my code not getting compiled?

Community
  • 1
  • 1
Zammy
  • 43
  • 2

3 Answers3

5

Here the type of ref is actually reference to int and not const reference to int. The const qualifier is ignored.

$8.3.2 says

Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef (7.1.3) or of a template type argument (14.3), in which case the cv-qualifiers are ignored.

const Ref_to_int ref; is equivalent to int& const ref; and not const int& ref.

Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
  • Or in another word, a `typedef` is not a simple text replacement... and `const` should be put *after* what they qualify for humans not to forget it. – Matthieu M. May 20 '11 at 11:45
1

Mixing const with a typedef doesn't work the way you're thinking; see this question for more info. These two lines are equivalent:

const Ref_to_int ref;
int& const ref;

You're looking for:

const int& ref;

One way to fix it is to include it in the typedef itself (although you should probably rename it then):

typedef const int& Ref_to_int;
Community
  • 1
  • 1
Michael Mrozek
  • 169,610
  • 28
  • 168
  • 175
0

You can't add additional specifiers to a typedef. It doesn't work like a macro.

Your code is effectively

int& const ref = 10;  // error

which isn't valid.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203