函数重载和模板扣除优先级 [英] Function overloading and template deduction priority

查看:110
本文介绍了函数重载和模板扣除优先级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下函数声明:

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

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

If I call f with a type with no relation with MyClass, the first version will be called. If I call f with a MyClass type (whatever the template parameters type are) then the second version will be called. But now, consider :

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

MyDerivedClass 将调用什么版本的函数$ c> type?

What version of the function will be called for a MyDerivedClass type ?

推荐答案

这是在标准的第13.3节。第13.3 / 1段规定:

This is handled in section 13.3 of the standard. Paragraph 13.3/1 states:


每个上下文都定义了候选函数集和
参数列表独特的方式。但是,一旦候选
函数和参数列表被识别,则在所有情况下选择
最佳函数是相同的: - 首先,
候选函数的子集 - 具有适当数量的参数和
满足某些其他条件 - 被选择以形成一组可行的
函数(13.3.2)。 - 然后根据
选择最佳可行函数,用于将每个
参数与每个可行函数的相应参数匹配所需的隐式转换序列(13.3.3.1)。
p>

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.

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

The first one is a better match since it won't involve any implicit conversion.

这篇关于函数重载和模板扣除优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆