源自std :: pinitializer_list是合法的吗?

发布于 2025-01-26 17:06:12 字数 1233 浏览 2 评论 0原文

我可以将std :: prinitizer_list列表作为基类吗?

template <typename T>
struct il : std::initializer_list<T>
{
    using base = std::initializer_list<T>;

    il(base list): base(list) {}

    const T &operator[](size_t i) const
        { return *(base::begin()+i); }
};

void print2(il<int> list)
{
    for (size_t i = 0; i < list.size(); i += 2)
        { std::cerr << list[i] << "; "; }

    std::cerr << std::endl;
}

int main()
{
    print2({0, 1, 2, 3, 4, 5, 6});
}

// The output: 0; 2; 4; 6; 

上面的代码在 gcc clang 。但是实际上有效吗?

cppreference.com 定义std :: prinita> std :: prinitionerizer_list 如下所示:

template< class T >
class initializer_list;

但这是否意味着std :: prinitizer_list是普通的类别吗?我认为这是C ++中的特殊对象。

Can I use std::initializer_list list as a base class?

template <typename T>
struct il : std::initializer_list<T>
{
    using base = std::initializer_list<T>;

    il(base list): base(list) {}

    const T &operator[](size_t i) const
        { return *(base::begin()+i); }
};

void print2(il<int> list)
{
    for (size_t i = 0; i < list.size(); i += 2)
        { std::cerr << list[i] << "; "; }

    std::cerr << std::endl;
}

int main()
{
    print2({0, 1, 2, 3, 4, 5, 6});
}

// The output: 0; 2; 4; 6; 

The code above works in both GCC and Clang. But is it actually valid?

The cppreference.com defines std::initializer_list as follows:

template< class T >
class initializer_list;

But does this mean that std::initializer_list is an ordinary class like any other? I thought it is kind of special object in C++.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

睫毛溺水了 2025-02-02 17:06:12

我在标准中可以找到的最佳参考是§16.4.5.1

以下子列在... [程序]将标准库类用作基础类的使用

,然后后来的在§16.4.5.5中

虚拟成员函数签名为C ++标准库中的基类定义

这似乎暗示了子类STDLIB类是公平的游戏。

当然,使用这些子类作为实际std :: prinitizer_list将很难。我可以在std :: prinistizer_list逐个值中想到的每种用例-is-Object-licting“>切成薄片在将其传递给大多数构造函数之前。

The best reference to this I can find in the standard is §16.4.5.1

The following subclauses specify constraints on ... [the program's] use of standard library classes as base classes

And then later in §16.4.5.5

Virtual member function signatures defined for a base class in the C++ standard library may be overridden in a derived class defined in the program

Which would seem to imply that it's fair game to subclass stdlib classes.

Of course, using those subclasses as an actual std::initializer_list is going to be difficult. Every use case I can think of in C++ for std::initializer_list takes one by value, so your subclass is going to get sliced before it ever gets passed to most constructors.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文