gpt4 book ai didi

c++ - 函数重载和模板推导优先级

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:46:56 27 4
gpt4 key购买 nike

考虑以下函数声明:

template<typename T> f(const T& x); // Version 1
template<typename T1, typename T2> f(const MyClass<T1, T2>& x); // Version 2

如果我用一个与 MyClass 无关的类型调用 f,将调用第一个版本。如果我用 MyClass 类型调用 f(无论模板参数类型是什么),那么将调用第二个版本。但是现在,考虑一下:

template<typename T1, typename T2, typename T3>
MyDerivedClass : public MyClass<T1, T2> {};

将为 MyDerivedClass 类型调用什么版本的函数?

最佳答案

这在标准的第 13.3 节中进行了处理。第 13.3/1 段指出:

Each of these contexts defines the set of candidate functions and the list of arguments in its own unique way. But, once the candidate functions and argument lists have been identified, the selection of the best function is the same in all cases: — First, a subset of the candidate functions—those that have the proper number of arguments and meet certain other conditions—is selected to form a set of viable functions (13.3.2). — Then the best viable function is selected based on the implicit conversion sequences (13.3.3.1) needed to match each argument to the corresponding parameter of each viable function.

第一个是更好的匹配,因为它不涉及任何隐式转换。

关于c++ - 函数重载和模板推导优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13900616/

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