I have this sample code ( below ), example1() method works with no problem, example2() is similar but I must force const_char to make it compile, although I consider as example1() method is not needed, example2() would be not needed either.
My question is, how can I modify add() method to make both compile or how must I correctly call buffer.add() in example2() without forcing const_cast? add() method is not modifying item, so const_cast is unnecessary. Which is the correct or suitable form?
Here’s the sample code:
template <class Item>
class Buffer
{
public:
Item * _pItems;
int _nItems;
// ... constructor / destructors etc
void add( const Item & item ) // or maybe Item const & item
{
_pItems[_nItems++] = item;
}
};
class MyClass
{
public:
// data
};
void example1( const MyClass & item )
{
Buffer<MyClass> buffer;
buffer.add( item ); // WORKS, no problem
}
void example2( const MyClass & item )
{
Buffer<MyClass *> buffer; // NOW with pointers to MyClass
//buffer.add( item ); // ERROR: 'Buffer<Item>::add' : cannot convert parameter 1 from 'const MyClass' to 'MyClass *const &'
buffer.add( const_cast<MyClass *>( &item ) ); // forcing const_cast WORKS
}
You should do something like :
because &item on a const MyClass is a Myclass const* not a MyClass*