gpt4 book ai didi

c++ - 为什么这些重载不是模棱两可的?

转载 作者:可可西里 更新时间:2023-11-01 18:33:05 24 4
gpt4 key购买 nike

以下代码使用 gcc 和 clang 编译良好。

template <typename T>
struct identity
{
typedef T type;
};

template <typename T>
void foo(typename identity<T>::type);

template <typename T>
void foo(T);

int main()
{
foo<int>(0);
}

看起来重载解析正在选择第一个重载(identity<T>::type 一个)。

有人可以解释为什么重载没有歧义吗?据我所知,它们之间的唯一区别是第一个参数是非推导上下文而第二个参数不是,但是由于我明确提供了模板参数,所以我不明白为什么这很重要。

最佳答案

两种重载都是可行的,但前者比后者更专业,因此它被重载决议选中。

根据 C++11 标准关于重载决议的第 13.3.3/1 段:

[...] 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,

— the context is an initialization by user-defined conversion (see 8.5, 13.3.1.5, and 13.3.1.6) and the standard conversion sequence from the return type of F1 to the destination type (i.e., the type of the entity being initialized) is a better conversion sequence than the standard conversion sequence from the return type of F2 to the destination type. [ ... ] or, if not that,

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

F1 and F2 are function template specializations, and the function template for F1 is more specialized than the template for F2 according to the partial ordering rules described in 14.5.6.2.

第 14.5.6.2/2 段概述了确定两个函数模板中哪一个比另一个更专业的过程:

Partial ordering selects which of two function templates is more specialized than the other by transforming each template in turn (see next paragraph) and performing template argument deduction using the function type. The deduction process determines whether one of the templates is more specialized than the other. If so, the more specialized template is the one chosen by the partial ordering process.

关于c++ - 为什么这些重载不是模棱两可的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16764285/

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