3

= delete; // not just for special member functions

 2 years ago
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.
= delete; // not just for special member functions

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


#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

Like this:

Loading...

Related


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK