How does the compiler know?

Warning: this post contains C++11 code. LB is not held responsible for loss of comprehension.
I'm trying to test how the compiler knows what types are what. The commented out lines are the ones which will not compile.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <typeinfo>

int main()
{
	std::cout << typeid(int(0)).name() << std::endl;
	std::cout << typeid(int()).name() << std::endl;
	std::cout << typeid(int(void)).name() << std::endl;
	std::cout << std::endl;
	auto x (int(0));
//	auto y (int());
//	auto z (int(void));
	std::cout << typeid(x).name() << std::endl;
	//std::cout << typeid(y).name() << std::endl;
	//std::cout << typeid(z).name() << std::endl;
	std::cout << std::endl;
	auto X = int(0);
	auto Y = int();
//	auto Z = int(void);
	std::cout << typeid(X).name() << std::endl;
	std::cout << typeid(Y).name() << std::endl;
	//std::cout << typeid(Z).name() << std::endl;
}
( see http://ideone.com/hMIBT )
i
FivE
FivE

i

i
i
In the first instance, int() is seen as a function signature. In the third instance, it is seen as an int (via calling the default constructor of an int?)

How does this work?
You're trying to change the type of NULL
If I'm not mistaken, the line
auto y (int());
is mistaken for a function signature for a function called y that accepts an unnamed function pointer to a function that returns an int and has no parameters, and will have its return type set after the parameter list. Try putting the int() in an extra set of parentheses.

The third instance is perfectly legal; the first one is only illegal because of a technicality. I've never used the int(void) syntax, so I can't comment on that.
I'm using MSC_VER 1600 and this is what I get.

1
2
3
4
5
6
7
std::cout << typeid(int(0)).name() << std::endl;  //int
std::cout << typeid(int()).name() << std::endl;   //unnamed function that takes a void param returns int
std::cout << typeid(int(void)).name() << std::endl;  //unnamed function that takes a void param and returns int

//...
auto X = int(0); //int
auto Y = int(); //int 


Once the type of the initializer has been determined, the compiler determines the type that will replace the keyword auto as if using the rules for template argument deduction from a function call. The keyword auto may be accompanied by modifies, such as const or &, which will participate in the type deduction.
Thanks, I wasn't too concerned with how auto works. I was more concerned with how the compiler figures out which types are what, and I thought auto could give some insignt.

@Telion: yep! I had forgotten about the extra set of parenthesis fix, I believe this is related to Most Vexing Parse?
Topic archived. No new replies allowed.