是否可以解释为什么以下代码无法按预期工作?在这种情况下,我假设两个static_asserts都会通过,尽管用Failed
指示的那个似乎没有被采用。
我对重载解决的理解是与参数最密切相关的类型。由于顶部定义是 C 样式数组,而底部定义是衰减的字符*;我觉得使用选择重载很奇怪。
MSVC和Clang似乎都有相同的行为。
error: static_assert expression is not an integral constant expression
note: non-constexpr function 'getStrLen' cannot be used in a constant expression
代码:
template<size_t N>
constexpr auto getStrLen(const char(&str)[N])
{
static_assert(N != 0, "Every literal string should have a null terminator");
return N - 1; // Remove
}
static_assert(getStrLen("") == 0, "Success");
auto getStrLen(const char *str)
{
return strlen(str);
}
static_assert(getStrLen("") == 0, "Failed");
根据 16.3.3.1.1 [over.ics.scs]/Table 13,精确匹配和数组到指针的转换具有相同的排名。根据 16.3.3 [over.best.match] 的匹配非template
优先于匹配template
。总之,采用char const*
的非模板函数是更好的匹配。
使这个函数成为一个template
,例如,通过给它一个默认的template
参数可能会解决这个问题。它有公平的机会使两者功能模棱两可。