I'm converting a large code to use custom shared pointers instead of raw pointers. I have a problem with overload resolution. Consider this example:
#include <iostream>
struct A {};
struct B : public A {};
void f(const A*)
{
std::cout << "const version\n";
}
void f(A*)
{
std::cout << "non-const version\n";
}
int main(int, char**)
{
B* b;
f(b);
}
This code correctly writes "non-const version" because qualification conversions play a role in ranking of implicit conversion sequences. Now take a look at a version using shared_ptr:
#include <iostream>
#include<memory>
struct A {};
struct B : public A {};
void f(std::shared_ptr<const A>)
{
std::cout << "const version\n";
}
void f(std::shared_ptr<A>)
{
std::cout << "non-const version\n";
}
int main(int, char**)
{
std::shared_ptr<B> b;
f(b);
}
This code doesn't compile because the function call is ambiguous.
I understand that user-defined deduction-guide would be a solution but it still doesn't exist in Visual Studio.
I'm converting the code using regexp because there are thousands of such calls. The regexps cannot distinguish calls that match the const version from those that match the non-const version. Is it possible to take a finer control over the overload resolution when using shared pointers, and avoid having to change each call manually? Of course I could .get() the raw pointer and use it in the call but I want to eliminate the raw pointers altogether.
shared_ptr
, as the container decreases the locality to memory accesses to that instance. If you have time, I'd encourage you to check out Herb Sutter's Smart Pointer Parameters post. – Petersen