In answering this question, I came across this difference in behaviour with respect to template instantiation.
Initially there is a function template
template <typename T> void my_callback(void* data) { … }
Now something requires the address of this - specifically a void*
, so the obvious approach is
bar(reinterpret_cast<void*>(&my_callback<int>));
However, with compiler versions pre gcc 4.5, this fails with a not-enough context... error. Fine - so the fix is to "cast" first - which forces instantiation, i.e:
void (*callback)(void*) = my_callback<int>;
bar(reinterpret_cast<void*>(callback));
This works fine.
Now the second scenario, rather than being a free function, it's a static member of a class template, i.e.
template <typename T>
struct foo
{
static void my_callback(void* data) {
T& x = *static_cast<T*>(data);
std:: cout << "Call[T] with " << x << std::endl;
}
};
Now, the original reinterpret_cast
works fine.
bar(reinterpret_cast<void*>(&foo<int>::my_callback));
So my question is - why this apparent difference in behaviour?