为什么 MSVC 2019 在以三元形式返回静态大小的数组时会失败?
Why does MSVC 2019 fail when returning a statically-sized array in a ternary?
我正在尝试将一些 library code 和 运行 编译成错误;我简化了示例,我有以下 MVCE,它无法使用 MSVC 2019 进行编译,并出现错误
error C2440: 'return': cannot convert from 'const char *' to 'const char (&)[20]'
static constexpr const char somethingWeird[] = "Well, that's odd...";
void fail() { throw 0; }
// This doesn't work
constexpr const char(&checkNullTerminatedGood(const char(&a)[20]))[20]{
return a[19] == char(0) ? decltype(a)(a) : (fail(), decltype(a)(a));
}
static constexpr const auto somethingElseNew = checkNullTerminatedGood(somethingWeird);
当我将三元运算符转换为适当的 if 语句时,代码编译得很好:
static constexpr const char somethingWeird[] = "Well, that's odd...";
void fail() { throw 0; }
// This works
constexpr const char(&checkNullTerminatedGood(const char(&a)[20]))[20]{
if (a[19] == char(0)) {
return decltype(a)(a);
} else {
return (fail(), decltype(a)(a));
}
}
static constexpr const auto somethingElseNew = checkNullTerminatedGood(somethingWeird);
这是 MSVC 中的错误吗?第一个片段使用 GCC 和 Clang 编译。
googling shows this is know problem 的一小部分声称已修复(但事实并非如此)。
C++ Overly aggressive decay of static array to pointer in ternary operator - Developer Community
Solution
by Leo Zhang [MSFT] Sep 07, 2017 at 02:35 AM
Thank you for your feedback! This issue has been fixed and it will be available in the next update to Visual Studio 2017. Thank you for helping us build a better Visual Studio!”
我正在尝试将一些 library code 和 运行 编译成错误;我简化了示例,我有以下 MVCE,它无法使用 MSVC 2019 进行编译,并出现错误
error C2440: 'return': cannot convert from 'const char *' to 'const char (&)[20]'
static constexpr const char somethingWeird[] = "Well, that's odd...";
void fail() { throw 0; }
// This doesn't work
constexpr const char(&checkNullTerminatedGood(const char(&a)[20]))[20]{
return a[19] == char(0) ? decltype(a)(a) : (fail(), decltype(a)(a));
}
static constexpr const auto somethingElseNew = checkNullTerminatedGood(somethingWeird);
当我将三元运算符转换为适当的 if 语句时,代码编译得很好:
static constexpr const char somethingWeird[] = "Well, that's odd...";
void fail() { throw 0; }
// This works
constexpr const char(&checkNullTerminatedGood(const char(&a)[20]))[20]{
if (a[19] == char(0)) {
return decltype(a)(a);
} else {
return (fail(), decltype(a)(a));
}
}
static constexpr const auto somethingElseNew = checkNullTerminatedGood(somethingWeird);
这是 MSVC 中的错误吗?第一个片段使用 GCC 和 Clang 编译。
googling shows this is know problem 的一小部分声称已修复(但事实并非如此)。
C++ Overly aggressive decay of static array to pointer in ternary operator - Developer Community
Solution
by Leo Zhang [MSFT] Sep 07, 2017 at 02:35 AM
Thank you for your feedback! This issue has been fixed and it will be available in the next update to Visual Studio 2017. Thank you for helping us build a better Visual Studio!”