During the 29th San Diego C++ Meetup fellow C++ enthusiast and contributor to my blog, Kobi, brought up something interesting about deleted functions and I wanted to share this little gem with you…
To my surprise the
= delete; postfix can be applied not only to special member functions like constructors or assignment operators, but to any free standing or member function!
Why would you want such sorcery you ask? Imagine you have a function like this:
void foo(void*) {}
On its own foo can be called with a pointer to any type without the need for an explicit cast:
foo(new int); // LEGAL C++
If we want to disable the implicit pointer conversions we can do so by deleting all other overloads:
template<typename T> void foo(T*) = delete;
Or the short and sweet C++20 syntax:
void foo(auto*) = delete;
To cast a wider net and delete all overloads regardless of the type and number of parameters:
template<typename ...Ts> void foo(Ts&&...) = delete;
Kobi found this on stack overflow of course 🙂
Example program:
delete.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
#include <iostream> #include <ios> using namespace std; void any_type(void* p) { cout << "any_type(void* p = " << hex << p << ")\n"; } void void_only(std::nullptr_t) { cout << "void_only(std::nullptr_t)\n"; } void void_only(void* p) { cout << "void_only(void* p = " << hex << p << ")\n"; } #if __cplusplus >= 202002L void void_only(auto*) = delete; // C++20 and newer... #else template<typename T> void void_only(T*) = delete; // prior to C++20... #endif // ALL other overloads, not just 1 pointer parameter signatures... template<typename ...Ts> void void_only(Ts&&...) = delete; int main() { any_type(new char); any_type(new short); any_type(new int); void_only(nullptr); // 1st overload void_only((void*)0xABC); // 2nd overload, type must be void* // void_only(0); // ERROR, ambiguous // void_only(NULL); // ERROR, ambiguous // void_only((long*)0); // ERROR, explicitly deleted // void_only((int*)1, (int*)2); // ERROR, also explicitly deleted } |
The other post https://stackoverflow.com/a/12877589/1463922 is almost 10 years old.
No surprise there. Deleted functions date back to C++11. Just comes to show one can study the language’s evolution and miss such obvious part. At least I didn’t know about it until recently.