C ++标准,重载函数分辨率/匹配 [英] C++ standard, overloaded function resolution/matching

查看:161
本文介绍了C ++标准,重载函数分辨率/匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++标准是否保证以下内容?

  template< typename T& 
void function(T(&)[1]);

template< typename T>
void function(T *);

int a [1];
function(a); //第一个函数被调用,而不是第二个版本


解决方案

是,这是保证,但原因不同于GMan说的。将选择长度为1的数组重载,因为它比模板函数部分顺序中的第二个更专门。基本上,这意味着 T(&)[1] 形式的参数将总是匹配第二个模板参数,形式为 T * / code>,因此当转换序列不决定时,将始终选择第一个重载。



从13.3.3开始:


给定这些定义,一个可行的
函数F1被定义为比另一个可行函数更好的
函数
F2参数i,ICSi(F1)是
不是比
ICSi(F2)更糟的转换序列,然后




    ICSj(F2)更好的转换序列,或者如果不是,则


  • p> F1是非模板函数,F2是模板函数专用化,
    或者如果不是,则


  • F1和F2是模板函数,F1的函数模板是
    ,比根据14.5.5.2中描述的部分
    排序规则的F2的模板

    或者如果不是




...


正常函数只受第一项影响;当任何模板函数在候选函数集合中时,第二或第三项目可以决定。我们想要的原因是我们想要能够写出看似模糊的模板重载。例如

 模板< class T> void f(T); 
template< class T> void f(T *);对于 int *

在C ++ 0x中,你甚至可以编写如下的声明:

  template< class ... Ts> void f(const Ts& ... args); 
template< class T,class ... Ts> void f(const T& a,const Ts& ... args);

,第二个将在至少有一个参数时被选择。


Does C++ standard guarantee the following?:

template<typename T>
void function(T (&)[1]);

template<typename T>
void function(T*);

int a[1];
function(a); // first function gets called, not second version

解决方案

Yes, this is guaranteed, but the reason is different than what GMan says. The "array of length 1" overload will be selected because it is more specialized than the second in template functions partial order. Basically, it means that an argument in the form T(&)[1] will always match the second template argument in the form T*, so the first overload will always be selected when conversion sequences don't decide.

From 13.3.3:

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 a non-template function and F2 is a template function specialization, or, if not that,

  • F1 and F2 are template functions, and the function template for F1 is more specialized than the tem- plate for F2 according to the partial ordering rules described in 14.5.5.2, or, if not that,

...

Normal functions are only affected by the first item; when any template functions are in the set of candidate functions, the second or third item can decide. The reason we want it like that is we want to be able to write seemingly ambiguous templated overloads. Eg.

template <class T> void f(T);
template <class T> void f(T*);

would otherwise be ambiguous for int*. In C++0x, you can even write declarations like:

template <class ...Ts>           void f(const Ts&... args);
template <class T, class ... Ts> void f(const T& a, const Ts&... args);

and the second will be selected whenever there is at least one argument.

这篇关于C ++标准,重载函数分辨率/匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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