Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

c++ - Does an lvalue argument prefer an lvalue reference parameter over a universal reference?

While playing with universal references, I came across this instance where clang and gcc disagree on overload resolution.

#include <iostream>

struct foo {};

template<typename T>
void bar(T&) { std::cout << "void bar(T&)
"; }

template<typename T>
void bar(T&&) { std::cout << "void bar(T&&)
"; }

int main()
{
    foo f;
    bar(f);  // ambiguous on gcc, ok on clang
}

gcc reports the call above is ambiguous. However, clang selects the T& overload and compiles successfully.

Which compiler is wrong, and why?

Edit:
Tested the same code on VS2013 Preview, and it agrees with clang; except Intellisense, which is on gcc's side :-)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The "universal reference" deduces the parameter to foo&. The first template also deduces the parameter to foo&.

C++ has a partial ordering rule for function templates that makes T& be more specialized than T&&. Hence the first template must be chosen in your example code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...