这实际上是模棱两可的吗? [英] Is This Actually Ambiguous?

查看:117
本文介绍了这实际上是模棱两可的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我知道代码中的花括号不仅仅意味着initializer_list:什么是花括号括起来的列表,如果不是intializer_list?

So I am aware that braces in code can mean more than just an initializer_list: What Is a Curly-Brace Enclosed List If Not an intializer_list?

但是他们应该默认使用什么?

But what should they default to?

例如,假设我定义了一个重载函数:

For example, say that I define an overloaded function:

void foo(const initializer_list<int>& row_vector) { cout << size(row_vector) << "x1 - FIRST\n"; }
void foo(const initializer_list<initializer_list<int>>& matrix) { cout << size(matrix) << 'x' << size(*begin(matrix)) << " - SECOND\n"; }

如果我呼叫foo({ 1, 2, 3 }),显然会呼叫1 st .而且,如果我呼叫foo({ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }),显然会调用2 nd .

If I call foo({ 1, 2, 3 }) the 1st will obviously be called. And if I call foo({ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }) the 2nd will obviously be called.

但是如果我打电话给我

foo({ { 1 }, { 2 }, { 3 } })

这些嵌套括号是int初始化程序还是initializer_list<int>初始化程序? gcc表示模棱两可,但是如果您使用该代码并在

Are those nested braces int-initializers or initializer_list<int> intializers? gcc says it's ambiguous But if you take that code and run it on http://webcompiler.cloudapp.net/ Visual Studio says it's just constructing an initializer_list<int>. Who's right? Should there be a default here?

推荐答案

规则位于 [over.ics .list] :

否则,如果参数类型为std::initializer_list<X>并且初始化列表的所有元素都可以隐式转换为X,则隐式转换序列是将列表中的元素转换为X所需的最差转换. ,或者,如果初始化列表中没有任何元素,则进行身份转换.

Otherwise, if the parameter type is std::initializer_list<X> and all the elements of the initializer list can be implicitly converted to X, the implicit conversion sequence is the worst conversion necessary to convert an element of the list to X, or if the initializer list has no elements, the identity conversion.

在两个重载中,最差的转换必要是标识转换.因此,我们有两个具有等级标识的隐式转换序列. [over.match.best] 中有一条规则相对于替代方案,更喜欢std::initializer_list<X>的列表初始化(因此,对于{1}std::initializer_list<int>int更可取),但是没有什么建议该规则应递归地应用.

In both your overloads, the worst conversion necessary is the identity conversion. So we have two implicit conversion sequences with rank identity. There is a rule in [over.match.best] which prefers a list-initialization of a std::initializer_list<X> over alternatives (so std::initializer_list<int> is preferred to int for {1}), but there nothing to suggest that this rule should apply recursively.

由于没有任何东西可以消除两个转换序列的歧义,因此该调用是模棱两可的. gcc和clang是正确的拒绝对象.

Since there's nothing to disambiguate the two conversion sequences, the call is ambiguous. gcc and clang are correct to reject.

这篇关于这实际上是模棱两可的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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