源自std :: pinitializer_list是合法的吗?
我可以将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;
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我在标准中可以找到的最佳参考是§16.4.5.1
,然后后来的在§16.4.5.5中
这似乎暗示了子类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
And then later in §16.4.5.5
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++ forstd::initializer_list
takes one by value, so your subclass is going to get sliced before it ever gets passed to most constructors.