initializer_list和默认构造函数重载解析 [英] initializer_list and default constructor overload resolution

查看:82
本文介绍了initializer_list和默认构造函数重载解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <initializer_list>
#include <iostream>
using namespace std;

struct Y {};

struct X
{
    X(initializer_list<Y>) { cout << "yay" << endl; }
    explicit X() { cout << "boo" << endl; }
};

X f()
{
    return {};
}

int main()
{
    f();

    return 0;
}

这将打印出 boo。为什么它不打印出是?

This prints out "boo". Why doesn't it print out "yay" ?

总有办法区分以下两种构造:

Is there anyway to differentiate the following two constructions:


  1. X()

  2. X {}

  1. X()
  2. X{}


  1. return X();

  2. return {};

  1. return X();
  2. return {};

void g(const X&)




  1. g(X())

  2. g({})

  1. g(X())
  2. g({})

谢谢。

推荐答案


总有办法区分以下两种结构:

Is there anyway to differentiate the following two constructions:

否。它们不是不同的构造。

No. They are not different constructs.

{}构造器语法的主要目的是引入 uniform 初始化,以使初始化工作在所有地方都相同。如果它们之间存在差异,那将不是统一的。

The primary purpose of the {} constructor syntax was to introduce uniform initialization, to have initialization work the same everywhere. If there was a difference between them, it wouldn't be uniform.

如果要使用空的初始值设定项列表构造函数,则必须声明要传递显式的初始化列表。像这样: return initializer_list< Y> {}; 当然,统一初始化的另一目的是不必键入太多类型名,因此您可以实现与 return {{}};

If you want to use the empty initializer list constructor, you have to state that you're passing an initializer list explicitly. Like this: return initializer_list<Y>{}; Of course, one of the other purposes of uniform initialization is to not have to type out typenames so much, so you can achieve the same effect with return {{}};

这篇关于initializer_list和默认构造函数重载解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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