= delete; // not just for special member functions
source link: https://vorbrodt.blog/2021/09/16/delete-not-just-for-special-member-functions/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
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
Like this:
Related
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK