【发布时间】:2012-07-27 23:58:55
【问题描述】:
我正在观察以下代码中的行为,我无法轻易解释并希望更好地理解理论。我似乎找不到涵盖这种特殊情况的在线文档来源或现有问题。作为参考,我使用 Visual Studio C++ 2010 编译并运行以下代码:
#include <iostream>
using namespace std;
struct Bottom_Class
{
template<typename This_Type>
void Dispatch()
{
// A: When this comment is removed, the program does not compile
// citing an ambiguous call to Print_Hello
// ((This_Type*)this)->Print_Hello();
// B: When this comment is removed instead, the program compiles and
// generates the following output:
// >> "Goodbye from Top Class!"
// ((This_Type*)this)->Print_Goodbye<void>();
}
void Print_Hello() {cout << "Hello from Bottom Class!" << endl;}
template<typename This_Type>
void Print_Goodbye() {cout << "Goodbye from Bottom Class!" << endl;}
};
struct Top_Class
{
void Print_Hello() {cout << "Hello from Top Class!" << endl;}
template<typename This_Type>
void Print_Goodbye() {cout << "Goodbye from Top Class!" << endl;}
};
template<typename Top_Type,typename Bottom_Type>
struct Merged_Class : public Top_Type, public Bottom_Type {};
typedef Merged_Class<Top_Class,Bottom_Class> My_Merged_Class;
void main()
{
My_Merged_Class my_merged_object;
my_merged_object.Dispatch<My_Merged_Class>();
}
为什么模板化成员函数与非模板化成员函数的情况不同?
编译器如何决定(在模板化的情况下)Top_Class::Print_Goodbye() 是适当的重载而不是 Bottom_Class::Print_Goodbye()?
提前感谢您的考虑。
【问题讨论】:
-
如果你把
Dispatch()设为全局函数,你还会看到这个问题吗?
标签: c++ visual-studio-2010 templates multiple-inheritance name-lookup