不,它们不一样。explicit
如果选择了该构造函数,则不允许隐式转换为该类型 - 参数中的隐式转换无关紧要。delete
如果选择了该构造函数,则不允许任何构造,并且可用于禁止隐式参数转换。
例如:
struct X {
explicit X(int ) { }
};
void foo(X ) { }
foo(4); // error, because X's constructor is explicit
foo(X{3}); // ok
foo(X{'3'}); // ok, this conversion is fine
这与构造函数是分开delete
的:
struct Y {
Y(int ) { }
Y(char ) = delete;
};
void bar(Y ) { }
bar(4); // ok, implicit conversion to Y since this constructor isn't explicit
bar('4'); // error, this constructor is deleted
bar(Y{'4'}); // error, doesn't matter that we're explicit
这两种技术也是正交的。如果您希望一个类型不能被隐式转换并且只能从一个 精确构造int
,您可以同时执行以下操作:
struct W {
explicit W(int ) { }
template <class T>
W(T ) = delete;
};
void quux(W );
quux(4); // error, constructor is explicit
quux('4'); // error, constructor is deleted
quux(4L); // error, constructor is deleted
quux(W{'4'}); // error, constructor is deleted
quux(W{5}); // ok