C++中的模板成员函数重载和多重继承
-
13-12-2019 - |
题
我正在观察下面的代码中的行为,我不能很容易地解释,并希望更好地理解理论。我似乎无法找到涵盖此特定情况的在线文档源或现有问题。作为参考,我正在使用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
方法, This_Type
是一样的 My_Merged_Class
.该 My_Merged_Class
有 二 名称为 Print_Hello
, ,当然编译器会有问题来区分它们。
呼吁 Print_Hello
在 Dispatch
, ,模板替换后,看起来像这样:
((My_Merged_Class*)this)->Print_Hello();
我希望上面的替换可以帮助你更好地看到为什么会有歧义。同样的问题 应该 实际上发生在 Print_Goodbye
, ,但它可能是你正在使用的编译器中的一个错误,让它通过。
其他提示
两个注释(正确地)使用GCC 4.6.3生成编译错误。可能是Microsoft编译器正在做一些不正确的东西。
➜ scratch g++ -O2 templ.cc
templ.cc: In member function ‘void Bottom_Class::Dispatch() [with This_Type = Merged_Class<Top_Class, Bottom_Class>]’:
templ.cc:42:48: instantiated from here
templ.cc:16:9: error: request for member ‘Print_Goodbye’ is ambiguous
templ.cc:22:10: error: candidates are: template<class This_Type> void Bottom_Class::Print_Goodbye()
templ.cc:30:10: error: template<class This_Type> void Top_Class::Print_Goodbye()
. 不隶属于 StackOverflow