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


2 Replies to “= delete; // not just for special member functions”

    1. 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.

Leave a Reply