2 ms·
= delete; allows your users to get a nice compiler error messages when they call a function you don't want them to call, by mistake. This can allow for instanc
by jcelerier 5y ago
= delete; allows your users to get a nice compiler error messages when they call a function you don't want them to call, by mistake.
This can allow for instance to explicitely erase overloads and "disable" functions or methods. For instance imagine that you don't want a function to be called with a float, just with a double, because having floats creeping in somewhere would be a bug and you want to catch as many bugs as possible: then you can just do the following.
void foo(float) = delete;
void foo(double) { }
int main()
{
// won't compile:
foo(1.23f);
// will compile:
foo(1.23);
}
without the following line:
void foo(float) = delete;
1.23f would be implicitely converted to a double instead of causing a compile error.
One case where I found it super useful is for instance to disable constructors taking a pointer when you have ctors taking a bool:
struct foo {
template<typename T>
foo(T*) = delete;
foo(bool);
};
int main()
{
void* x = nullptr;
// won't compile: foo f(x);
// won't compile: foo g("blablaba");
}
this (rightly) causes a compile error on both the creation of f and g, while if foo(T*) = delete; was not there then conversions from ptr to bool would happen:
struct foo {
foo(bool);
};
int main()
{
void* x = nullptr;
foo f(x); // compiles :'(
foo g("blablaba"); // compiles :'(
}