为什么std :: initializer_list不支持std :: get<>,std :: tuple_size和std :: tuple_element [英] Why does std::initializer_list not support std::get<>, std::tuple_size and std::tuple_element
问题描述
为什么 std :: initializer_list
不支持 std :: get<>
, std :: tuple_size
和 std::tuple_element
?像现在一样,它在 constexpr
表达式中经常使用,例如
Why does std::initializer_list
not support std::get<>
, std::tuple_size
and std::tuple_element
? It is used a lot in constexpr
expressions as is right now, for example,
std::max({1, 2, 3, 4, 5});
如果它做得很酷,可能会发生以下情况
And if it did cool things like the following would be possible
auto [x, y] = {1, 2};
那么为什么 std :: initializer_list
不支持这些?据我所知,在运行时无法构造 std :: initializer_list
,因此大小始终由用户确定.
So why does std::initializer_list
not support these? As far as I know there is no way to construct a std::initializer_list
at runtime, so the size is always fixed by the user.
下面是一个示例,该示例说明了如何在编译时获取 std :: intializer_list<>
的大小
Below is an example of how one can get the size of an std::intializer_list<>
at compile time
#include <iostream>
#include <initializer_list>
using std::cout;
using std::endl;
template <typename...> struct WhichType;
template <typename Type>
constexpr int size_init_list(std::initializer_list<Type> il) {
return il.end() - il.begin();
}
int main() {
constexpr auto size = size_init_list({1, 2, 3});
cout << static_cast<int>(std::integral_constant<int, size>{}) << endl;
return 0;
}
推荐答案
即使 std :: initializer_list
的大小是编译时常量,该大小也不是该类型的一部分.每个 int
的初始值设定项列表都具有相同的类型,即 std :: initializer_list< int>
.并且 std :: tuple_size< std :: initializer_list< int>> :: value
只能有一个可能的值.因此很明显,它不能用于获取初始化程序列表的实际大小.完全没有任何意义.
Even though the size of a std::initializer_list
is a compile-time constant, the size isn't part of the type. Every initializer list of int
s has the same type, namely std::initializer_list<int>
. And std::tuple_size<std::initializer_list<int>>::value
can only have one possible value. So obviously it cannot be used to get the actual size of an initializer list. It makes no sense to define it at all.
这篇关于为什么std :: initializer_list不支持std :: get<>,std :: tuple_size和std :: tuple_element的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!