繁体   English   中英

C ++中的模板成员函数重载和多重继承

[英]Template Member Function Overloading and Multiple Inheritance in C++

我观察下面代码中的行为,我不能轻易解释,并希望理解更好的理论。 我似乎找不到涵盖这种特殊情况的在线文档来源或现有问题。 作为参考,我使用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()?

提前感谢您的考虑。

两条注释(AFAIK正确)都会在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()

Dispatch方法中, This_TypeMy_Merged_Class相同。 My_Merged_Class两个名称为Print_Hello ,当然编译器会有问题来区分它们。

模板替换后,在DispatchPrint_Hello的调用如下所示:

((My_Merged_Class*)this)->Print_Hello();

我希望上面的替代可以帮助你更好地了解为什么会有歧义。 Print_Goodbye实际上应该出现同样的问题,但它可能是您正在使用的编译器中的一个错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM