const TypedeffedIntPointer not equal to const int *
I have the following C++ code:
typedef int* IntPtr;
const int* cip = new int;
const IntPtr ctip4 = cip;
I compile this with Visual Studio 2008 and get the following error:
error C2440: 'initializing' : cannot convert from 'const int *' to 'const IntPtr'
Clearly my understanding of typedefs is not what is should be.
The reason I'm asking, I'm storing a pointer type in a STL map. I have a function that returns a const pointer which I would like to use to search in the map (using map::find(const key_type&). Since
const MyType*
and
const map<MyType*, somedata>::key_type
is incompatible, I'm having problems.
Regards Dirk
When you write const IntPtr ctip4
, you are declaring a const-pointer-to-int, whereas const int * cip
declares a pointer-to-const-int. These are not the same, hence the conversion is impossible.
You need to change the declaration/initialization of cip to
int * const cip = new int;
To resolve this issue in your example, you need to either change the key type of the map to const MyType *
(whether or not it makes sense depends on your application, but I think that changing a MyType object via a pointer used as key in the map is unlikely), or fall back to const_casting the parameter to find:
#include <map>
int main()
{
const int * cpi = some_func();
std::map<const int *, int> const_int_ptr_map;
const_int_ptr_map.find(cpi); //ok
std::map<int *, int> int_ptr_map;
int_ptr_map.find(const_cast<int *>(cpi)); //ok
}
const IntPtr
is the same as int* const
, not const int*
.
That is, it is a const
pointer to an int
, not a pointer to a const int
.
A solution would be to provide two typedefs:
typedef int* IntPtr;
typedef const int* ConstIntPtr;
and use ConstIntPtr
when you need a pointer to a const int
.
上一篇: 模板函数给出编译错误