如何使用概念检查模板参数是固定长度n的容器? 我想有一个概念,该概念检查类型是否是容器 固定长度。类型可以是C风格的数组,std ::数组,std :: span或定制的容器。我可以检查 con ...

问题描述 投票:0回答:1
或定制的容器。我可以检查 集装箱条件如下所示,但我无法确定 检查长度条件。

template <typename T, size_t N> concept fixed_container = requires (T const& t) { {std::size(t)} -> std::same_as<size_t>; {std::begin(t)}; {std::end(t)}; } // && std::declval<T>().size() == N // Error: 'declval() must not be used!' // && T::size() == N // Error: 'call to non-static member function without an object argument' ; // These should all be correct static_assert( fixed_container<std::array<double, 3>, 3>); static_assert(!fixed_container<std::array<double, 3>, 4>); static_assert( fixed_container<std::span<double, 3>, 3>); static_assert(!fixed_container<std::span<double, 3>, 4>); static_assert( fixed_container<double[3], 3>); static_assert(!fixed_container<double[3], 4>);

任何想法?
Edit:
块
requires (T const& t) { {std::size(t)} -> std::same_as<size_t>; {std::begin(t)}; {std::end(t)}; }

可以用一条线代替
std::ranges::sized_range<T>

[...],但我无法检查一下长度条件。
您需要单独处理它。例如,您可能会执行以下操作(这是受评论中提到的类似问题的启发):

template<typename T> constexpr std::size_t get_fixed_size() { if constexpr (std::is_array_v<T>) return std::extent_v<T>; else if constexpr (requires { T::extent; }) return T::extent; // For std::span else if constexpr (requires { std::tuple_size<T>::value; }) return std::tuple_size<T>::value; // For std::array else return 0; } template<typename T, std::size_t N> concept fixed_container = requires(T const& t) { { std::size(t) } -> std::same_as<std::size_t>; { std::begin(t) }; { std::end(t) }; } && get_fixed_size<std::remove_cvref_t<T>>() == N;
c++ templates containers c++20 c++-concepts
1个回答
6
投票
看到现场演示

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.