假设我有一个FunctionWrapper
这样定义的类:
struct FunctionWrapper
{
FunctionWrapper(std::function<void()> f);
// ... plus other members irrelevant to the question
};
我想防止从std::function<void()>
to进行隐式转换FunctionWrapper
,但允许FunctionWrapper
使用大括号初始化语法构造 a (即,使用带有单个参数的列表初始化)。换句话说,我想要这样:
void foo();
void wrap(FunctionWrapper);
wrap(foo); // (1) error
wrap({foo}); // (2) OK
wrap(FunctionWrapper{foo}); // (3) OK
有没有办法做到这一点?我在上面定义类的方式不是这样:这允许隐式转换,所以 (1) 编译。
如果我添加explicit
到构造函数:
struct FunctionWrapper
{
explicit FunctionWrapper(std::function<void()> f);
// ... plus other members irrelevant to the question
};
它也无济于事,因为这“太过分”并且不允许(2)和(1)。
有没有办法实现“中间立场”并让(2)编译而(1)产生错误?