سؤال

إنني ألاحظ سلوكًا في الكود أدناه لا أستطيع شرحه بسهولة وأرغب في فهم النظرية بشكل أفضل.يبدو أنني لا أستطيع العثور على مصدر توثيق عبر الإنترنت أو سؤال موجود يغطي هذا الموقف بالذات.كمرجع، أنا أستخدم 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, ، ولكن قد يكون هناك خطأ في المترجم الذي تستخدمه والذي يسمح له بالمرور.

نصائح أخرى

كلا التعليقات (AFAIK بشكل صحيح) إنشاء خطأ في تجميع مع GCC 4.6.3.قد يكون برنامج Microsoft Compiler يفعل شيئا غير صحيح.

giveacodicetagpre.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top