2010-11-30 56 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;