gpt4 book ai didi

C++ 函数匹配优先级

转载 作者:IT老高 更新时间:2023-10-28 23:19:23 26 4
gpt4 key购买 nike

我有一个关于 c++ 函数匹配优先级的简单问题。假设我有这样的代码:

#include <iostream>

void func(const char*)
{
std::cout << "const char*" << std::endl;
}

template<int N>
void func(const char (&) [N])
{
std::cout << "const char (&) [N]" << std::endl;
}

int main(int argc, char* argv[])
{
func("Hello world");
return 0;
}

代码的结果是(Apple LLVM version 6.1.0 (clang-602.0.49) (based on LLVM 3.6.0svn)):

const char*

我认为 "Hello world" 的字面量类型应该是 const char[]。为什么 const char* 版本的优先级高于 const char (&)[] 版本?

最佳答案

重载分辨率尝试找到最佳转换。以下段落列出了可以区分两种转换的相关要点:

Standard conversion sequence S1 is a better conversion sequence than standard conversion sequence S2 if

  • S1 is a proper subsequence of S2 (comparing the conversion sequences in the canonical form defined by 13.3.3.1.1, excluding any Lvalue Transformation; the identity conversion sequence is considered to be a subsequence of any non-identity conversion sequence) or, if not that,

  • the rank of S1 is better than the rank of S2, or S1 and S2 have the same rank and are distinguishable by the rules in the paragraph below, or, if not that,

  • […]

虽然函数模板的特化产生了一个带有恒等转换的参数,但带有 char const* 的非模板重载需要数组到指针的转换。直觉上,我们会说前者是更好的匹配,因此应该被选中。但是,数组到指针的转换是左值转换,不包括在第一个要点中。由于它具有精确匹配排名,因此转换的排名与 char const (&)[N] 的转换排名没有什么不同,后者也具有精确匹配排名。 “以下段落中的规则”也无法区分转换,因为它们仅解决派生到基础的转换等,而不是数组到指针。

实际上,转换为 char const (&)[N] 并没有更好的办法。但重载决议区分模板:

Given these definitions, a viable function F1 is defined to be a better function than another viable function F2 if for all arguments i, ICSi(F1) is not a worse conversion sequence than ICSi(F2), and then

  • for some argument j, ICSj(F1) is a better conversion sequence than ICSj(F2), or, if not that,

  • […]

  • F1 is not a function template specialization and F2 is a function template specialization, or, if not that,

因此选择了非模板重载。

关于C++ 函数匹配优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29961100/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com