Overload Resolution with Deleted Constructor C++

32 Views Asked by At

I'm sure this question exists elsewhere, but can't find an answer. I've noticed that when a constructor is defined as deleted, it makes that type take part in overload resolution. In other words, if you were to remove the deleted constructor entirely, the overload resolution would not even consider that type.

Here is some simple code. Hopefully I'm showing this correctly, because I haven't tried such a simple case yet:

struct SomeType { .... SomeType(const void*)=delete; .... };
void DoStuff(const void *ptr);
void DoStuff(const SomeType &obj);

SomeType test_obj;
DoStuff( test_obj );

If SomeType has a deleted constructor defined as SomeType(const void*)=delete;, the compiler will complain about overload ambiguity. Why is this? And is there any way to stop this behavior? Doesn't it make more sense for a deleted function to have the opposite effect? To ensure that it doesn't take part in overload resolution?

The only way I've found to fix this issue is to declare the constructor as explicit:

explicit SomeType(const void*)=delete;

This appears to delete the constructor and conversions. Is this the correct way to deal with this situation? Or am I missing something? Thanks!

Note: I'm using Visual Studio 2022 with v142 build tools and C++20

Edit: Okay, my sample code compiles without issues, so I'm thinking maybe this is only an issue if the types have other conversions. While the sample code doesn't directly demonstrate the problem, it shows a simpler version of my actual code. I will continue to mess around to see if I can figure out exactly what causes the ambiguity error to get thrown. But if anyone can give me some advice on why a deleted function would cause ambiguity, that would be great.

0

There are 0 best solutions below