I have redefined the << operator and I want it to take a reference of pointer.
class foo
{
foo();
virtual ~foo();
void operator << (BaseService*& iRight);
}
Somewhere in the code, having a foo instance, and a service which is a specialization of the BaseService class I do :
Service* service_pointer = new Service();
foo_instance << service_pointer;
But I get this error :
error: no match for ‘operator<<‘in ‘foo_instance << service_pointer’
note: candidates are: void foo::operator<<(BaseService*&)
Nothing changes if I dynamic_cast my service_pointer to BaseService
Service* service_pointer = new Service();
foo_instance << dynamic_cast<BaseService*>(service_pointer);
Any idea ?
The first version does not work because you can’t pass in a reference to a pointer to a subtype and rightly so: What if the implementation of
operator<<made the pointer point to an instanceMyService(which is a subclass ofBaseService, but not ofService)? Clearly it would be illegal for aService*to point to aMyService. So passing in aService*is not allowed.The second version is not allowed because
dynamic_castdoes not return an l-value, so you can’t pass it as a non-const reference.The only thing you can do is define another variable of type
BaseService*and pass that as an argument to<<. If<<then reassigns the pointer, that change will be visible for the newly created variable only and not affectServicePointer.That being said (and not knowing your use case) I have to advice you that having
operator<<take a non-const reference to anything as its right operand strikes me as bad practice. You wouldn’t usually expect<<to modify it’s right operand.