views:

188

answers:

3

Why does this fail to compile? (g++-4.5)

template < typename U >
static void h () {
}

int main () {
  auto p = &h<int>; // error: p has incomplete type
}

EDIT: Here is a work-around:

template < typename U >
static void h () {
}

int main () {
  typedef decltype (&h<int>) D;
  D p = &h<int>; // works
}
A: 

It does not compile because type of 'p' is not known to the compiler which is a must in C++ unlike some other languages.

Try

template < typename U > 
static void h () { 
} 

int main () { 
  auto void (*p)() = &h<int>; 
} 
Chubsdad
The `auto` keyword is used for automatic type deduction. A C++0x feature.
dirkgently
Ok, but in my real code, h takes a lot of other parameters depending on U and other templates, and I don't want to specify them all, as the type of p should be known to the compiler.
Thomas
@dirkgenly: Oh. I am still at C++03 where 'auto' is for automatic variables
Chubsdad
the question is probably about the C++ 0x `auto` which should be able to determine the type automatically, the the "old" "this is a stack variable" - auto.
peterchen
Comeau online comiles it fine
Chubsdad
gcc 3.4.5 comiles it fine
doc
sorry, by auto I mean the c++0x auto
Thomas
`auto` is a pure nonsense here.
doc
+4  A: 

In C++0x this is guaranteed to work. However in C++03 this wasn't working (the initializer part, that is) and some compilers apparently don't support it yet.

Furthermore, I remember that the C++0x wording is not clear what happens with &h<int> when it is an argument to a function template and the corresponding parameter is deduced (this is what auto is translated to, conceptionally). The intention is, however, that it is valid. See this defect report where they designed the wording, the example by "Nico Josuttis" and their final example.

There is another rule that the wording enforces but compilers are not correctly implementing. For example, see this clang PR.

Johannes Schaub - litb
A: 

Try

 auto p  = static_cast<void(*)()>(& h<int>);

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?

edit: this compiles on gcc so please give me a reason why downvoted. edit2: I didn't receive an answer so I assume that's because you're an idiot.

doc
I am not the downvoter :) Anyhow I am not sure to understand your logic: since you are static_casting to a compile time known type, what's the use for auto?
Francesco
doc
@Francesco: they got the same result with `typedef` as with a static_cast. I thought he wanted C++0x `auto` keyword...
doc
@doc: I agree that the typedef suffer from the same issue: you must specify by hand the type and so the advantage of automatic type deduction is lost.
Francesco