universal reference vs const reference priority?

a 夏天 提交于 2019-12-20 18:53:34

问题


When I consider the two following overloads:

template <class... T> void f(const T&... x);
template <class T> void f(const T& x);

I have the guarantee that f(x) will always call the second function and will never lead to an ambiguity. In a sense the second version is universally prioritized compared to the first one for one argument whatever its type is.

Now consider the situation where there is a universal reference and a const reference versions of a function:

template <class T> void f(T&& x);
template <class T> void f(const T& x);

My question is: is their a universal priority between these two functions regardless of the type of x (r-value reference, reference, cv-qualifiers, pointer...) like in the previous case? (and if yes, what is the priority ?)


回答1:


There is not a universal priority between these two functions. They compete equally in the overload resolution algorithm. In general the so-called "universal reference" wins unless const T& is an exact match, and there the const T& wins.

struct A {};

int
main()
{
    f(std::declval<A>());  // calls f<A>(A&&), #1
    f(std::declval<const A>());  // calls f<const A>(const A&&), #1
    f(std::declval<A&>());  // calls f<A&>(A&), #1
    f(std::declval<A&&>());  // calls f<A>(A&&), #1
    f(std::declval<const A&&>());  // calls f<const A>(const A&&), #1
    f(std::declval<const A&>());  // calls f<A>(const A&), #2
}

Good advice is to never overload like this.



来源:https://stackoverflow.com/questions/18264829/universal-reference-vs-const-reference-priority

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!