3
int main(int argc, char* argv[]) {
  const int i = 10;
  using Type = typename std::conditional<false, int, int&>::type;
  const Type r = i; // It seems this 'const' does not have any effect.
  std::cout << r << std::endl;
}

The above code cannot compile on gcc4.8.1 -std=c++11, and the error message goes as following: "invalid initialization of reference of type 'Type {aka int&}' from expression of type 'const int'. But, it will work if I change the code like this:

int main(int argc, char* argv[]) {
  const int i = 10;
  using Type = typename std::conditional<false, const int, const int&>::type;
  Type r = i;
  std::cout << r << std::endl;
}

Is there any body can show me the reason?

mumu
  • 197
  • 7

2 Answers2

2

In the first example, the const has no effect because it binds to the wrong type: after the reference rather than before. See https://www.securecoding.cert.org/confluence/display/cplusplus/DCL33-CPP.+Never+qualify+a+variable+of+reference+type+with+const+or+volatile for some details that may help, but basically:

const int& // reference to immutable int
int const& // reference to immutable int
int& const // immutable reference to int

Of course, all references are immutable (cannot be reseated), so the last one, which you have, is a bit useless. It happens because you apply the const after the reference has already been applied to the type, which gives you the third example I wrote rather than the first or second.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • (Though typing out `int& const` like that is not valid. That sort of thing is only allowed when `const` is applied to a typedef or template parameter that happens to be a reference type.) – aschepler Mar 23 '14 at 04:47
0

You can also change

  const int i = 10;

to

  int i = 10;

to make it work.

when you say

using Type = typename std::conditional<false, int, int&>::type;

it is equivalent to:

typedef int& Type;

When you say

const Type r = i;

What you are saying is

int& const r = i;

That's not the same thing as

const int& r = i;

The difference between those was explained by John Zwinck in his answer.

R Sahu
  • 204,454
  • 14
  • 159
  • 270