Let's say I have a class FunctionWrapper
defined like this:
struct FunctionWrapper
{
FunctionWrapper(std::function<void()> f);
// ... plus other members irrelevant to the question
};
I'd like to prevent implicit conversions from std::function<void()>
to FunctionWrapper
, but allow constructing a FunctionWrapper
using a brace initialisation syntax (that is, using list initialisation with a single argument). In other words, I'd like this:
void foo();
void wrap(FunctionWrapper);
wrap(foo); // (1) error
wrap({foo}); // (2) OK
wrap(FunctionWrapper{foo}); // (3) OK
Is there a way to achieve that? The way I've defined the class above is not it: this allows implicit conversions, so (1) compiles.
If I add explicit
to the constructor:
struct FunctionWrapper
{
explicit FunctionWrapper(std::function<void()> f);
// ... plus other members irrelevant to the question
};
it doesn't help either, as that goes "too far" and disallows (2) as well as (1).
Is there a way to achieve "middle ground" and have (2) compile while (1) produces an error?