C++ quick tips: Deleted free functions
I’m sure that we all know about the = delete
keyword introduced in
c++11 and its application to class member functions. I’m not sure
though if everyone knows that = delete
can be applied to free
standing functions as well.
Free standing functions application
Main reason to have this feature is to limit the number of overloads
and narrow down implicit conversion. std::cref
and std::ref
are a
good example. cppreference for std::ref lists several overloads. The following are deleted:
|
|
This is to prevent overload resolution to accept incovations like:
|
|
So, attempts to use std::ref
or std::cref
with rvalues is basically forbidden as it would result in undefined behaviour.
Exotic use case
= delete
usage is not limited only to function overloads! There’s nothing preventing us from using it on any function.
Consider the following:
|
|
The above will result in build error:
|
|
Following the = delete
declaration, usage of printf
has been effectively forbidden.
Let’s not forget though that this is a hack since printf
is declared more than once and
compiler will, rightly so, complain about this fact as well:
|
|