I don't understand the need for the static_cast in the following C++ code snippet (tested with GCC-4.7):
#include <cstdio>
class Interface
{
public:
virtual void g(class C* intf) = 0;
virtual ~Interface() {}
};
class C
{
public:
void f(int& value)
{
printf("%d\n", value);
}
void f(Interface* i)
{
i->g(this);
}
template <typename T>
void f(T& t);
//void f(class Implementation& i);
};
class Implementation : public Interface
{
public:
Implementation(int value_) : value(value_) {}
void g(C* intf)
{
intf->f(value);
}
private:
int value;
};
int main()
{
C a;
Implementation* b = new Implementation(1);
//a.f(b); // This won't work: undefined reference to `void C::f<Implementation*>(Implementation*&)'
a.f(static_cast<Interface*>(b));
delete b;
return 0;
}
If I omit the static_cast, I get a linker error because it wants to use:
template <typename T>
void f(T& t);
instead of:
void f(Interface* i);
On the other hand, if I replace the templated method with the following (commented out in the above snippet):
void f(class Implementation& i);
then I don't get errors and I can see that the "correct" method is called at run-time (that is:
void f(Interface* i);
).
Why does the declaration of the template method affect name lookup? Many thanks in advance,