【发布时间】:2022-06-10 18:13:28
【问题描述】:
我在标准库中搜索了相当长的时间,但找不到计算 std::array 类型或 std::span 类型或 c-array 类型的元素计数的模板函数的名称。我的意思是类似于下面示例代码中的get_element_count。
我不是在寻找解决方案,get_element_count 工作正常。我只是相信已经存在一个标准函数。
函数必须将类型作为参数,例如std::tuple_size,例如但需要更通用。
所以问题是:标准库中该函数的名称是什么?我对@user17732522 的回答很满意,因为它不存在,所以我找不到它。
#include <iostream>
#include <array>
#include <span>
#include <type_traits>
template<typename>
inline constexpr size_t get_element_count = 0;
template<typename T, size_t N>
inline constexpr size_t get_element_count<std::array<T, N>> = N;
template<typename T, size_t N>
inline constexpr size_t get_element_count<std::span<T, N>> = N;
template<typename T, size_t N>
inline constexpr size_t get_element_count<T[N]> = N;
int main ()
{
std::array<char, 7> a = {'0','1','2','3','4','5','6'};
std::span b = a;
std::span<char, 7> c = a;
char d[7] = {'0','1','2','3','4','5','6'};
long e[7] = { 0L, 1L, 2L, 3L, 4L, 5L, 6L};
std::cout << get_element_count<decltype(a)> << std::endl;
std::cout << get_element_count<decltype(b)> << std::endl;
std::cout << get_element_count<decltype(c)> << std::endl;
std::cout << get_element_count<decltype(d)> << std::endl;
std::cout << get_element_count<decltype(e)> << std::endl;
}
因为有些人要求举个例子,在哪里需要而不是只使用这样的编译时函数:
template <typename T, size_t N>
struct S {T t; size_t n = N;};
using A = std::array<int, 5>;
using B = std::span<int, 5>;
template <typename T>
using C = S<typename T::value_type, 2 * get_element_count<T>>;
using D_double = C<A>;
using E_double = C<B>;
【问题讨论】:
-
我已经阅读了几次这个问题,但我仍然看不到问题所在。
array的大小为constexpr,不是吗? (编辑:由于缺乏细节,我投票决定关闭) -
@TedLyngmo size 成员是 consexpr 但您需要一个实例来调用它。在我的示例中,我当然可以将 decltype(x) 替换为 x.size(),但这只是一个示例。我需要类型的大小。我需要它来写一些 sfinae 条件。
-
应该是
std::tuple_size_v。但是,他们删除了对固定范围std::span(github.com/cplusplus/papers/issues/838) 的支持,并且还没有添加对原始数组 (github.com/cplusplus/papers/issues/1240) 的支持。我想你现在必须像以前一样自己动手了。 -
@PatrickFromberg 我只是说这是标准库为此目的使用的常用接口。没有其他的。它的支持目前(在我看来)不完整。我想知道为什么他们最终决定不使用
std::span的元组接口。 LWG 问题 (cplusplus.github.io/LWG/issue3212) 仅表示该决定是在“关于预期设计的冗长讨论”之后做出的- -
目前还不清楚问题是什么。显示的编译良好,并生成一个 7 列表。 “我需要类型的大小”是什么意思?
标签: c++ c++20 typetraits