我不明白以下 C++ 代码片段(使用 GCC-4.7 测试)中对 static_cast 的需求:
#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;
}
如果我省略了 static_cast,我会得到一个链接器错误,因为它想使用:
template <typename T>
void f(T& t);
代替:
void f(Interface* i);
另一方面,如果我用以下内容替换模板化方法(在上面的代码段中注释掉):
void f(class Implementation& i);
然后我没有收到错误,我可以看到在运行时调用了“正确”方法(即:
void f(Interface* i);
)。
为什么模板方法的声明会影响名称查找?提前谢谢了,