[英]Overload resolution C-style strings
Would it be possible to explain why the following code ain't working as expected? 是否有可能解释为什么以下代码无法按预期运行? In this case, I would assume that both static_asserts would pass, though the one indicated with
Failed
doesn't seem to be taken. 在这种情况下,我假设两个static_asserts都会通过,尽管似乎未采用
Failed
指示的那个。
My understanding of overload resolution would be that the type most closely linked to the argument. 我对重载解决方案的理解是,该类型与参数最紧密地联系在一起。 As the top definition is a C-Style array, while the bottom definition is a decayed char*;
由于顶部定义是C-Style数组,而底部定义是衰减的char *; I find it strange that the select overload gets used.
我发现选择重载被使用很奇怪。
Both MSVC as Clang seem to have the same behavior. MSVC和Clang似乎都具有相同的行为。
error: static_assert expression is not an integral constant expression
note: non-constexpr function 'getStrLen' cannot be used in a constant expression
The code: 编码:
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 \0
}
static_assert(getStrLen("") == 0, "Success");
auto getStrLen(const char *str)
{
return strlen(str);
}
static_assert(getStrLen("") == 0, "Failed");
An exact match and array to pointer conversion have the same rank according to 16.3.3.1.1 [over.ics.scs]/Table 13. A matching non- template
is preferred over a matching template
according to 16.3.3 [over.best.match]. 根据16.3.3.1.1 [over.ics.scs] /表13,精确匹配和数组到指针的转换具有相同的等级。根据16.3.3 [over.best],匹配的非
template
优先于匹配的template
。比赛]。 In summary, the non-template function taking a char const*
is the better match. 总而言之,采用
char const*
的非模板函数是更好的匹配。
Making this function a template
, eg, by giving it a defaulted template
parameter may solve the problem. 使此功能成为
template
(例如,通过为其提供默认的template
参数)可以解决该问题。 It has a fair chance to make the two function ambiguous. 有机会使这两个功能变得模棱两可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.