Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator overload of class wrapped in smart pointers

I've been trying to make some operator overloads (* and +) on a class which is wrapped in smart pointers.

auto p = std::make_unique<Polynomial<T>>();

When I try to overload it using normal overloading, it obviously asks for the smart pointer types.

Edit, so:

std::unique_ptr<Polynomial<T>> operator+(const std::unique_ptr<Polynomial<T>>& right);

template<class T>std::unique_ptr<Polynomial<T>> Polynomial<T>::operator+(const std::unique_ptr<Polynomial<T>>& right) {
    //Do stuff
}

And the error:

Error from trying to use the + operator

So how do you go about overloading the normal operators when the class is encapsulated in a smartpointer?

like image 237
Dennis Avatar asked Jun 03 '15 14:06

Dennis


1 Answers

Don't.

Run those operations on the pointees, not on the pointers:

*p = *p + *p

It would be very confusing for users of your code if suddenly pointers had completely different and unexpected semantics.

It would be confusing for you, too.

like image 83
Lightness Races in Orbit Avatar answered Sep 23 '22 17:09

Lightness Races in Orbit