【发布时间】:2012-12-19 10:43:21
【问题描述】:
我不明白为什么下面的代码打印的是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; }
}
编辑:
更奇怪的是this(这一次它只是 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>
如果删除了复制构造函数,那为什么还有歧义?!
【问题讨论】:
-
为什么会打印
int?您正在尝试创建Value的实例,因此您将转换为Value。 -
@R.MartinhoFernandes:我在调用
Value的构造函数,它的参数类型是int,那为什么Convertible()不被转换成int呢?为什么隐式复制构造函数完全隐藏了我显式定义的构造函数,而不是导致歧义错误? -
liveworkspace.org/code/3ZUTMY$0 ...您使用哪个编译器?
-
@Mehrdad 它将被转换为
int,然后转换为Value。 -
我现在明白了这个问题,但是你所说的“奇怪”是正常的:删除的函数不会从重载决议中删除。如果他们被选中,他们只会使程序格式错误。这是一个功能。
标签: c++ visual-c++ implicit-conversion