std :: initializer_list的实现 [英] Implementation of std::initializer_list

查看:88
本文介绍了std :: initializer_list的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究 initializer_list 的实现方式,因此我找到了标准的18.9节,并找到了一个简单的界面。我认为制作自己的版本(将其命名为 MyNamespace :: InitializerList 和一个用例)将是有益的:

I have been looking at how the initializer_list is implemented so I found section 18.9 of the standard and found a simple enough looking interface. I thought it would be instructive to make my own version which I named MyNamespace::InitializerList and a use case:

template<class T>
class ArrayPrinter
{
public:
    ArrayPrinter(MyNamespace::InitializerList<T> list)
    {
        for (auto i : list) cout << i << endl;
    }
};

...

ArrayPrinter ap{ {1,2,3} };

我很惊讶地发现这不起作用,编译器抱怨找不到它合适的构造函数(它想给我3个参数,但是18.9节仅描述了默认的构造函数)。

I was surprised to find that this did not work and the compiler complained that it couldn't find a suitable constructor (it wanted to give me 3 arguments but section 18.9 only describes a default constructor).

经过一番摆弄之后,我发现我的类必须准确命名 std :: initializer_list 才能正常工作。我也可以将 std :: initializer_list 别名为 MyNamespace ,但不能为 MyNamespace别名: :InitializerList as std :: initializer_list

After a bit of fiddling I found that my class had to be named exactly std::initializer_list in order to work. I could also alias std::initializer_list it into MyNamespace but I could not alias MyNamespace::InitializerList asstd::initializer_list.

似乎这不是真的是语言功能,因为它取决于标准库

我的问题的重点是为什么名称如此重要,它试图传递给构造函数的那三个参数是什么?

The main point to my question is why the name is so important and what were those 3 arguments it was trying to pass to the constructor?

推荐答案

名称很重要,因为标准表明它是必需的。该标准需要某种方式让您能够说:可以向此构造函数传递包含T类型的序列值的括号初始化列表。这样便被命名为 std :: initializer_list

The name is important because the standard says it is. The standard needs some way for you to be able to say, "this constructor can be passed a braced-init-list containing a sequence values of the type T". That way was given the name "std::initializer_list".

您不能创建一个包含所有 initializer_list 语言属性。您可以制作一个满足标准18.9节指定的类型的条件。但是您会注意到,唯一指定的构造函数是 default 构造函数。创建带有实际元素的 initializer_list 的唯一方法取决于编译器,而不是用户代码。

You cannot make a class that has all of the language properties of initializer_list. You can make one that satisfies the conditions of the type specified by section 18.9 of the standard. But you'll notice that the only constructor specified there is a default constructor. The only way to create an initializer_list with actual elements relies on the compiler, not user-land code.

因此,您无法复制有关 initializer_list 的所有内容。就像您无法复制 std :: type_info 一样。 C ++标准库不是可选

So you can't replicate everything about initializer_list. Just as you can't replicate std::type_info. The C++ standard library is not optional.

这篇关于std :: initializer_list的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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