2010-11-30 55 views
7

請看看這個代碼並運行它:
我發現了非常奇怪的錯誤:
錯誤1個錯誤C2663:「分配器:: allocate_help」:2個重載沒有'this'指針的合法轉換沒有法律轉化爲this指針

template<class FailureSignal> 
class Allocator 
{ 
private: 
    template<class Exception,class Argument> 
    void allocate_help(const Argument& arg,Int2Type<true>) 
    { 
    } 

    template<class Exception,class Argument> 
    std::nullptr_t allocate_help(const Argument& arg,Int2Type<false>) 
    { 
     return nullptr; 
    } 

public: 
    template<class T> 
    void Allocate(signed long int nObjects,T** ptr = 0)const 
    { 
    allocate_help<std::bad_alloc>(1,Int2Type<true>()); 
    } 

}; 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    Allocator<int> all; 
    all.Allocate<int>(1); 
    return 0; 
} 

我完全不明白這個err味精。希望有人能幫助我。謝謝。

+1

無法按照您的要求進行編譯。 `Int2Type`沒有被聲明/定義 – 2010-11-30 20:02:56

回答

12

我注意到Allocate被宣佈爲const,但allocate_help不是 - 可能與問題有關嗎?

+1

是的,謝謝。他們能不能提供更多信息性的信息? – 2010-11-30 19:48:05

0

我有同樣的錯誤也是由const造成的,但方式有點不同。

我有兩個虛擬函數(過載),一個是const,另一個不是。這是造成這個問題的原因。如果你想超載一個函數,就會發現它們都需要匹配,如果它們是const或者不是。

virtual void value() const = 0; 
virtual void value(MyStruct & struct) = 0; 

上面的代碼會導致這個錯誤。修復方法是將第二個聲明更改爲:

virtual void value(MyStruct & struct) const = 0;