2009-03-16 3 views
0
#include <iostream> 
using namespace std; 

/* 

     TA  <-- defines static function 
    / \ 
    |  B <-- subclass TA, inherits it so B::StaticFunc can be used. 
    \ /
     C  <-- want to inherit static func from A, subclass B privately 
*/ 

template <class T> class TA 
{ 
public: 
    // return ptr to new instance of class T 
    static T * instance() 
    { 
     static T inst; 
     return &inst; 
    } 
}; 


class B : public TA<B> 
{ 
public: 
    void Func() { cout << "B" << endl; } 
}; 


/* HERE: class C : public TA<C> */ 
class C : public TA<C>, private B 
{ 
public: 
    void Func() { cout << "C" << endl; } 
}; 

int main() 
{ 
    C test(); 

    B::instance()->Func(); 
    C::instance()->Func(); 

    /* 
    Expected output: 
     B 
     C 

    Actual error: 
     error: `instance' is not a member of `C'| 

     If i do not subclass B with C, then it compiles. However, I need 
     C to provide some other functionality and but a subclassable Singleton 
    */ 

    return 0; 
} 

답변

2

내가 (4.3.3 ++ g과) 다른,보다 합리적인 오류 얻을 가입에 정적 메소드 disapears이 명시 적으로 instance의 버전을 지정하여 고정 할 수 있습니다

tst.cpp: In function ‘int main()’: 
tst.cpp:49: error: reference to ‘instance’ is ambiguous 
tst.cpp:22: error: candidates are: static T* TA<T>::instance() [with T = B] 
tst.cpp:22: error:     static T* TA<T>::instance() [with T = C] 

C에서 사용되어야합니다 :

class C : public TA<C>, private B 
{ 
public: 
    using TA<C>::instance; 
    void Func() { cout << "C" << endl; } 
}; 
+0

당신이 이길 수 있습니다. 나는 그 사용법을 처음 접했습니다. – mawt

+0

다중 상속으로 인해 함수 이름이 모호한 모든 경우에 이와 같이 "using"을 사용할 수 있습니다. –

관련 문제