=delete for templates 和 just using explicit 之间有什么区别?

What's the difference between =delete for templates and just using explicit?

我正在阅读 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;
};

有没有理由写上面的代码而不是下面的这段代码?

struct OnlyDouble
{
    explicit void f(double d);
};

有什么区别,或者是否有一些我不知道的额外行为?

两件事:

  1. explicit 对函数无效,因此 explicit void f(double); 无法编译。
  2. explicit 不会阻止参数的隐式转换。

也就是说,即使比较是在:

struct OnlyDouble
{
    OnlyDouble(double d);
    template<class T> OnlyDouble(T) = delete;
};

struct OnlyDouble
{
    explicit OnlyDouble(double d);
};

你是对的,两者都会出错:

OnlyDouble od = 42;

但以下第一个格式错误,第二个格式正确:

OnlyDouble od(42);