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?
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);
}
Drop const
void constructVector( const T* item);
or
Use:
void constructVector(const T* item)
{
std::vector<const T*> v;
v.push_back(item);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With