how to overload unique_ptr in a class . i am getting compilation error

70 views Asked by At
std::unique_ptr<Manager>& checkManager(std::unique_ptr<Manager> &p1) 
 {
   if(p1 && p1->getName().find("Manager") != std::string::npos ){
      std::cout<<"Manager exists"<<endl;
   }
   return p1;
 }

//overloading by unique ptr
 std::unique_ptr<Manager> checkManager(std::unique_ptr<Manager> p1) //by value passing uniq ptr
 {
   if(p1 && p1->getName().find("Manager")!=std::string::npos) {
      std::cout<<"Manager exists"<<endl;
   }
   return std::move(p1);
 }

i have overloaded these methods . in main when i am calling both i am getting error that function argument does not match . how to call these two methods separately from main.

Below is how i am calling these methods

 auto& resultRef = checkManager(mp1);  // it gives compilation error
 auto result = checkManager(std::move(mp1)); // it works

Below is the error: more than one instance of overloaded function "checkManager" matches the argument list:

1

There are 1 answers

1
Artyer On BEST ANSWER

You want the first overload to be called for lvalues and the second for rvalues.

You can do just that by making the second overload take an rvalue reference:

std::unique_ptr<Manager>& checkManager(std::unique_ptr<Manager> &p1) {
    // ...
    return p1;
}

std::unique_ptr<Manager> checkManager(std::unique_ptr<Manager> &&p1) {
    // ...
    return std::move(p1);
}

Before, when called with an lvalue, even though unique_ptr isn't copyable, it is still just a good a match (T& doesn't beat T when passed a T lvalue).

Now, the second overload cannot be called with an lvalue, so it is no longer ambiguous.