c 11 – 为什么“矢量v {{5,6}};`工作?我以为只有一双{}被允许?

c 11 – 为什么“矢量v {{5,6}};`工作?我以为只有一双{}被允许?,第1张

概述给定一个具有两个构造函数的类A,取initializer_list< int>和initializer_list< initializer_list< int>>分别 A v{5,6}; 打电话给前者,和 A v{{5,6}}; 呼吁后者,如预期. (clang3.3,显然gcc的行为有所不同,看到答案,标准要求什么?) 但是如果我删除第二个构造函数,那么A v {{5,6}};仍然编译,它使用第 给定一个具有两个构造函数的类A,取initializer_List< int>和initializer_List< initializer_List< int>>分别
A v{5,6};

打电话给前者,和

A v{{5,6}};

呼吁后者,如预期. (clang3.3,显然gcc的行为有所不同,看到答案,标准要求什么?)

但是如果我删除第二个构造函数,那么A v {{5,6}};仍然编译,它使用第一个构造函数.我没想到这个
我认为A v {5,6}将是访问initializer_List< int>的唯一方法.构造函数.

(我在std :: vector和this question I asked on Reddit播放时发现了这一点,但是我创建了自己的A类,以确保它不仅仅是std :: vector的界面的怪癖.)

解决方法 我想这个 answer might be relevant.

Yes,this behavIoUr is intended,according to §13.3.1.7 Initialization
by List-initialization

When objects of non-aggregate class type T are List-initialized (8.5.4),overload resolution selects the constructor in two phases:

— Initially,the candIDate functions are the initializer-List constructors (8.5.4) of the class T and the argument List consists of
the initializer List as a single argument.

— If no viable initializer-List constructor is found,overload resolution is performed again,where the candIDate functions are all
the constructors of the class T and the argument List consists of the
elements of the initializer List.

在gcc我试过你的例子.我得到这个错误:

error: call of overloaded 'A(<brace-enclosed initializer List>)' is ambiguous

如果我使用三套大括号,gcc会停止抱怨.即:

#include <iostream>#include <vector>#include <initializer_List>struct A {    A (std::initializer_List<int> il) {         std::cout << "First." << std::endl;    }    A (std::initializer_List<std::initializer_List<int>> il) {         std::cout << "Second." << std::endl;    }};int main(){    A a{0}; // first    A a{{0}}; // compile error    A a2{{{0}}}; // second    A a3{{{{0}}}}; // second}

试图镜像向量的构造函数,这里是我的结果:

#include <iostream>#include <vector>#include <initializer_List>struct A {    A (std::initializer_List<int> il) {         std::cout << "First." << std::endl;    }    explicit A (std::size_t n) {        std::cout << "Second." << std::endl;    }    A (std::size_t n,const int& val) {        std::cout << "Third." << std::endl;    }    A (const A& x) {        std::cout << "Fourth." << std::endl;    }};int main(){    A a{0};    A a2{{0}};    A a3{1,2,3,4};    A a4{{1,4}};    A a5({1,4});    A a6(0);    A a7(0,1);    A a8{0,1};}main.cpp:23:10: warning: braces around scalar initializer    A a2{{0}};         ^~~1 warning generated.First.First.First.First.First.Second.Third.First.
总结

以上是内存溢出为你收集整理的c 11 – 为什么“矢量v {{5,6}};`工作?我以为只有一双{}被允许?全部内容,希望文章能够帮你解决c 11 – 为什么“矢量v {{5,6}};`工作?我以为只有一双{}被允许?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1234518.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存