在回答这个问题的研究中,我发现(之前不知道)gcc和clang允许char
数组作为模板参数,如果它们被声明为static
。例如,这段代码可以在gcc和clang中编译:
#include <type_traits>
template <int N, const char (&string)[N]>
auto foo()
{
if constexpr (string[0] == 'i')
return 0;
else
return 3.14f;
}
void bar()
{
static constexpr char string1[] = "int";
static constexpr char string2[] = "float";
auto i = foo<sizeof(string1), string1>();
auto f = foo<sizeof(string2), string2>();
static_assert(std::is_same_v<decltype(i), int>);
static_assert(std::is_same_v<decltype(f), float>);
}
MSVC也允许这样做。但是,为了使其在MSVC中工作,我必须在全局命名空间中声明这两个字符串。然后它就能正常工作了。
所以我的问题是:标准对此有什么说法?哪个编译器(如果有的话)是正确的?
更新:
这个问题已经在VS 2019版本16.4(MSVC v19.24)中得到了修复:https://developercommunity.visualstudio.com/content/problem/341639/very-fragile-ice.html
static constexpr char p[] = {'i','n','t'}
,它将在 MSVC 下失败,如 此错误所述。 - stevecu