4

考虑下面的代码:

struct Bar{};

struct Foo
{
    Foo() = default;
    Foo(const Bar&) {}
    Foo(const Foo&) = delete;

    // IMPLICIT conversion to Bar
    operator Bar(){return {};}
};

int main() 
{
    Foo f1;
    Foo f2(static_cast<Bar>(f1)); // this is OK
    Foo f3(f1); // does not compile, why not implicit conversion to `Bar`?
}

该类Bar有一个用户定义的转换运算符 to Foo,它接受Bar&s。但是,在 的最后一行中main,我本来希望Foo f1将其转换为Bar然后传递给Foo(const Bar&). 但是,仅考虑已删除的构造函数Foo(const Foo&) = delete;。我知道这个构造函数是一个更好的匹配,但为什么也不是Foo(const Bar&)重载集中,为什么编译器不执行隐式转换?

4

1 回答 1

6

它是首选的,因为查找和重载解决方案发生在已删除的成员函数上记录已删除的定义之前。

也就是说,重载决议不会考虑说明delete符和你的电话:

Foo f3(f1);

由于f1是 type FooFoo(const Foo&)是直接参数类型匹配。因此,在重载分辨率方面的排名高于Foo(const Bar&).

于 2015-11-18T21:43:02.267 回答