为什么 VC++ 编译此代码而 Clang 不会
Why does VC++ compile this code while Clang won't
clang 版本:X86-64 clang 3.9.1
VC++ 版本:x86-64 CL 19 RC
我希望它能编译,因为 const char* 可以隐式转换为 A 并且 A 可以转换为 B。有趣的是,clang 声明 const char [5] 不能转换为 A?注意:我现在明白它不是标准行为,但我仍然想知道 VC++ 接受此代码的原因,即导致它的语言扩展?
clang 给出的错误:
no viable conversion from 'const char [5]' to 'B'
clang给出的提示:
note: candidate constructor not viable: no known conversion from 'const char [5]' to 'A' for 1st argument
note: candidate constructor (the implicit copy constructor) not viable: no known conversion from 'const char [5]' to 'const B &' for 1st argument
#include <string>
#include <vector>
struct A
{
std::string m_test;
A(const char* test)
: m_test(test)
{
}
};
struct B
{
A m_a;
B( A a )
: m_a(a)
{
}
};
int main()
{
B test = "test";
}
只允许一个隐式 user-defined 转换,参见 [class.conv]/4:
At most one user-defined conversion (constructor or conversion function) is implicitly applied to a single value.
所以它似乎是 Microsoft C++ 扩展,实际上,如果您禁用 MSVC 扩展 (/Za
),您将得到相同的错误:
error C2440: 'initializing': cannot convert from 'const char [5]' to 'B'
至于原因 - 它看起来像是某种 "multiple implicit conversions" 扩展,但文档中没有提及它。甚至还有一个 bug submitted,它应该被修复,但我想那没有成功。
clang 版本:X86-64 clang 3.9.1
VC++ 版本:x86-64 CL 19 RC
我希望它能编译,因为 const char* 可以隐式转换为 A 并且 A 可以转换为 B。有趣的是,clang 声明 const char [5] 不能转换为 A?注意:我现在明白它不是标准行为,但我仍然想知道 VC++ 接受此代码的原因,即导致它的语言扩展?
clang 给出的错误:
no viable conversion from 'const char [5]' to 'B'
clang给出的提示:
note: candidate constructor not viable: no known conversion from 'const char [5]' to 'A' for 1st argument
note: candidate constructor (the implicit copy constructor) not viable: no known conversion from 'const char [5]' to 'const B &' for 1st argument
#include <string>
#include <vector>
struct A
{
std::string m_test;
A(const char* test)
: m_test(test)
{
}
};
struct B
{
A m_a;
B( A a )
: m_a(a)
{
}
};
int main()
{
B test = "test";
}
只允许一个隐式 user-defined 转换,参见 [class.conv]/4:
At most one user-defined conversion (constructor or conversion function) is implicitly applied to a single value.
所以它似乎是 Microsoft C++ 扩展,实际上,如果您禁用 MSVC 扩展 (/Za
),您将得到相同的错误:
error C2440: 'initializing': cannot convert from 'const char [5]' to 'B'
至于原因 - 它看起来像是某种 "multiple implicit conversions" 扩展,但文档中没有提及它。甚至还有一个 bug submitted,它应该被修复,但我想那没有成功。