Question

Consider the piece of code:

class T;

void constructVector(const T* item)
{
   std::vector<T*> v;
   v.push_back(item);
}

I get an error with MSVC 2010 compiler:

error: C2664: 'void std::vector<_Ty>::push_back(_Ty &&)' : cannot convert parameter 1 from 'const T *' to 'T *&&' with [ _Ty=T * ] Conversion loses qualifiers

I can see this particular conversion is illegal, but I don't believe my code is semantically wrong. I also believe there's push_back(const T&) variant, why isn't that matched to my call?

Was it helpful?

Solution

Because that's a vector of non-const pointers. It won't convert a const pointer to a non-const pointer. That would defeat the purpose of const.

I believe that the push_back(const T&) is not what you're looking for, because that makes the T object itself const, it does not change the type of T from (*) to (const *).

You could make the vector a vector of const pointers :

void constructVector(const T* item)
{
    std::vector<const T*> v;
    v.push_back(item);
 }

Or you could change your function to take a non-const pointer :

 void constructVector(T* item)
 {
    std::vector<T*> v;
    v.push_back(item);
 }

OTHER TIPS

Drop const

void constructVector( const T* item);

or

Use:

void constructVector(const T* item)
{
   std::vector<const T*> v;
   v.push_back(item);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top