一个左值参数喜欢一个通用引用的左值引用参数? [英] Does an lvalue argument prefer an lvalue reference parameter over a universal reference?

查看:207
本文介绍了一个左值参数喜欢一个通用引用的左值引用参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用通用引用时,我遇到这个实例,其中clang和gcc在重载解析上不同意。

  #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 上面的调用是不明确的。但是, clang 会选择 T&



编辑:

在VS2013 Preview上测试了相同的代码,它同意clang;除非Intellisense,它在gcc的一侧: - )

解决方案

通用引用推导参数 foo& 。第一个模板还将参数推导为 foo&



C ++对函数模板有部分排序规则,使 T& T&&< / code>。因此,必须在您的示例代码中选择第一个模板。


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&)\n"; }

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

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 :-)

解决方案

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.

这篇关于一个左值参数喜欢一个通用引用的左值引用参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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