문제

저는 관찰하는 행위에서 아래 코드 수 없는 쉽게 설명한 것과 같은 이론을 이해하의 더 낫습니다.하는 온라인 설명서 원본 또는 기존의 질문에는 이 특정한 상황이다.참고로 나는 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_HelloDispatch, 후 템플릿체는 다음과 같습니다.

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

난 위의 교체를 더 잘 이유가 있습니다.동 실제로 발생할 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()
.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top