Why does this fail to compile? (g++-4.5)
template < typename U >
static void h () {
}
int main () {
auto p = &h; // error: p has inco
Try
auto p = static_cast(& h);
Because gcc treats templated function as overloaded one. From the gcc's point of view it's like you would have h(int param)
and h(float param)
- which one the compiler has to choose?
I noticed what was the problem in older versions of gcc, but I'll try to explain it more verbosely. GCC couldn't deduce the type, because templated function was treated like overloaded one. It was basically like you would have the following:
void h(int)
{
}
void h(float)
{
}
void (*p)(int) = & h; //ok
void (*p)(float) = & h; //ok
auto p = & h; //error: which version of h?
For gcc h
was just like overloaded h
function with endless alternatives depending onT
parameter. With the code provided in question it was O.K. to do the following:
void (*p)() = & h;
(that's why I don't get typedefed "work-around")
As I thought OP wanted to use c++11 auto
keyword as suggested by a tag, I statically casted h
to void(*)()
, which is kind of no-operation, just to trick gcc, because it was not able to deal with templated functions and auto
correctly.
Functions void h
and void h
should be of course treated like different functions with the same pointer type and not overload versions of h
function. When instantiated they should behave like void hInt()
and void hFloat()
and you should be able to use auto like here:
void hInt()
{
}
void hFloat()
{
}
auto p = hInt;
p = hFloat;
But for some reason for gcc they were like overloaded versions of h
.
Please give a reason for downvotes.