为什么是std :: array< T,0>不是空的? [英] Why is std::array< T, 0 > not empty?

查看:147
本文介绍了为什么是std :: array< T,0>不是空的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定任何 std :: array< T,0> ,为什么它不为空?我的意思是空如:

  std :: is_empty< std :: array< int,0> > :: value 

返回 false

  #include< iostream> 
#include< tuple>
#include< array>

struct Empty {};

int main()
{
std :: cout< sizeof(std :: tuple< int>)< std :: endl;
std :: cout<< sizeof(std :: tuple< int,Empty>)< std :: endl;
std :: cout<< sizeof(std :: tuple< int,std :: array< int,0>>)< std :: endl;
}

产生

  4 
4
8

意味着 std :: array< int,0> ,不应用空基本优化(EBO)。



这看起来很奇怪,因为 std :: tuple<> (注意:没有模板参数)是空的, std :: is_empty< std :: tuple<>> :: value 会产生 true 。 >

问题:为什么,考虑到 0 的大小已经是 std :: array

标准没有说明是否是有意的或是在标准中的监督?

解决方案< tuple 数组应该为空,你看到的是实现细节,但没有理由使 tuple< > 非空,而对于数组< T,0> 是非空的,有很好的理由,请考虑:

  std :: array< int,sizeof ...(values)> = {{values ...}}; 

当参数包为空时,你会得到:

  std :: array< int,0> = {{}}; 

对于初始化器有效,对象需要一个成员,它不能 int [0] 因为你不能有零大小的数组作为成员,所以一个可能的实现是 int [1]



一个实现不必特殊情况下整个数组,它只能做:

  T m_data [N == 0? 1:N]。 

,所有其他成员的工作方式完全相同(假设 end / code>定义为 begin()+ N


Given any std::array< T, 0 >, why is it not empty? I mean "empty" as in:

 std::is_empty< std::array< int, 0 > >::value

returning false and

 #include <iostream>
 #include <tuple>
 #include <array>

 struct Empty {};

 int main()
 {
     std::cout << sizeof(std::tuple<int>) << std::endl;
     std::cout << sizeof(std::tuple<int,Empty>) << std::endl;
     std::cout << sizeof(std::tuple<int,std::array<int,0>>) << std::endl;
 }

yields

 4
 4
 8

which means, that for std::array<int,0>, the empty base optimization (EBO) is not applied.

This seem especially strange to me given that std::tuple<> (note: no template parameters) is empty, i.e., std::is_empty<std::tuple<>>::value does yield true.

Question: Why is that, given that size 0 is already a special case for std::array? Is it intentional or an oversight in the standard?

解决方案

The standard doesn't say anything about whether tuple or array should be empty, what you're seeing are implementation details, but there's no reason to make tuple<> non-empty, whereas there is a good reason for array<T, 0> being non-empty, consider:

std::array<int, sizeof...(values)> = { { values... } };

When the parameter pack is empty you'd get:

std::array<int, 0> = { { } };

For the initializer to be valid the object needs a member, which cannot be int[0] because you can't have zero-sized arrays as members, so a possible implementation is int[1]

An implementation doesn't have to special case the whole array, it can just do:

T m_data[N == 0 ? 1 : N];

and all other members work exactly the same way (assuming end() is defined as begin()+N)

这篇关于为什么是std :: array&lt; T,0>不是空的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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