繁体   English   中英

转换运算符+转换构造函数=不直观的行为?

[英]Conversion operator + conversion constructor = unintuitive behavior?

我不明白为什么下面的代码打印struct Value而不是int (这意味着转换构造函数转换为Value而不是int )。 (Visual C ++ 2012)

为什么会这样? 为什么编译器完全忽略Value(int)构造函数?

#include <iostream>
#include <type_info>

using namespace std;

struct Value { Value(int) { } };

struct Convertible
{
    template<class T>
    operator T() const
    { throw typeid(T).name(); }
};

int main()
{
    try { Value w((Convertible())); }
    catch (char const *s) { cerr << s << endl; }
}

编辑:

更奇怪的是这次 (这次只是C ++ 11,在GCC 4.7.2上):

#include <iostream>
#include <typeinfo>

using namespace std;

struct Value
{
    Value(Value const &) = delete;
    Value(int) { }
};

struct Convertible
{
    template<class T>
    operator T() const
    { throw typeid(T).name(); }
};

int main()
{
    try { Value w((Convertible())); }
    catch (char const *s) { cerr << s << endl; }
}

这使:

source.cpp: In function 'int main()':
source.cpp:21:32: error: call of overloaded 'Value(Convertible)' is ambiguous
source.cpp:21:32: note: candidates are:
source.cpp:9:3: note: Value::Value(int)
source.cpp:8:3: note: Value::Value(const Value&) <deleted>

如果复制构造函数被删除,那为什么会有歧义?!

在第一个示例中,Visual Studio不正确; 这个电话很模糊。 gcc在C ++ 03模式下打印:

source.cpp:21:34: error: call of overloaded 'Value(Convertible)' is ambiguous
source.cpp:21:34: note: candidates are:
source.cpp:9:5: note: Value::Value(int)
source.cpp:6:8: note: Value::Value(const Value&)

回想一下,复制构造函数是隐式默认的。 管理段落是13.3.1.3由构造函数[over.match.ctor]初始化

当类类型的对象被直接初始化[...]时,重载决策选择构造函数。 对于直接初始化,候选函数是正在初始化的对象的类的所有构造函数。

在第二个例子中,删除的函数同样参与重载决策; 一旦选择了已删除函数的程序格式错误,它们只会在重载已解决后影响编译。 标准中的激励示例是一个只能从浮点类型构造的类:

struct onlydouble {
  onlydouble(std::intmax_t) = delete;
  onlydouble(double);
};

我已经尝试过你的代码(仅限Visual Studio版本)。

由于你有一个内置的复制CTOR,我想你的主要等于:

int main()
{
    try { Value w((struct Value)(Convertible())); }
    catch (char const *s) { cerr << s << endl; }
}

编译器已选择使用您的副本CTOR,而不是Value(int)。

将其更改为:

int main()
{
    try { Value w((int)(Convertible())); }
    catch (char const *s) { cerr << s << endl; }
}

它打印“int”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM