I was reading Explicitly defaulted and deleted special member functions, and saw that in order to call only the function f
with double
and avoid an implicit conversion, one could write this (from the same page):
struct OnlyDouble
{
void f(double d);
template<class T> void f(T) = delete;
};
Is there a reason why one would write the code above instead of this code below?
struct OnlyDouble
{
explicit void f(double d);
};
Any difference, or is there some extra behavior that I don't know of?
CodePudding user response:
Two things:
explicit
is not valid for functions so theexplicit void f(double);
doesn't compile.explicit
doesn't prevent implicit conversions of arguments.
That is, even if the comparison were between:
struct OnlyDouble
{
OnlyDouble(double d);
template<class T> OnlyDouble(T) = delete;
};
and
struct OnlyDouble
{
explicit OnlyDouble(double d);
};
You're right that both would error on:
OnlyDouble od = 42;
but following is ill-formed for the first and well-formed for the second:
OnlyDouble od(42);