I ran into a compilation problem that I don't understand, I simplified it for explanation below.
In principle, it includes the presence of two different getters (const and non-const one) that return a container (a map in this example) with a constant, respectively, not a constant value_type.
What puzzles me is that in the example below, the compiler cannot use const getter for a non-constant object:
#include "stdafx.h" #include <utility> #include <map> class TestObject { public: TestObject() {} virtual ~TestObject() {} }; typedef std::pair<const TestObject*, const TestObject*> ConstTestObjectPair; typedef std::pair<TestObject*, TestObject*> TestObjectPair; class Test { TestObject* m_pObject; public: Test() {m_pObject = new TestObject();} virtual ~Test() {delete m_pObject;} std::map<unsigned, ConstTestObjectPair> GetObject() const { std::map<unsigned, ConstTestObjectPair> map; map.insert(std::make_pair(0, std::make_pair(m_pObject, m_pObject))); return map; } std::map<unsigned, TestObjectPair> GetObject() { std::map<unsigned, TestObjectPair> map; map.insert(std::make_pair(0, std::make_pair(m_pObject, m_pObject))); return map; } }; int _tmain(int argc, _TCHAR* argv[]) { Test* pTest = new Test(); const Test* pConstTest = pTest; std::map<unsigned, ConstTestObjectPair> CTO = pTest->GetObject(); // Not compiling, I don't get why!!! CTO = pConstTest->GetObject(); std::map<unsigned, TestObjectPair> TO = pTest->GetObject(); //TO = pConstTest->GetObject(); // Not working, this is expected return 0; }
I tried with both VS2010 and gcc, and none of them accepts compiling this code. Here is the compilation error returned by VS2010:
1>c:\test.cpp(48): error C2440: 'initializing' : cannot convert from 'std::map<_Kty,_Ty>' to 'std::map<_Kty,_Ty>' 1> with 1> [ 1> _Kty=unsigned int, 1> _Ty=TestObjectPair 1> ] 1> and 1> [ 1> _Kty=unsigned int, 1> _Ty=ConstTestObjectPair 1> ] 1> No constructor could take the source type, or constructor overload resolution was ambiguous
Can someone explain to me why the compiler cannot find / use the correct prototype for a non-constant object?
Thanks a lot!