简体   繁体   English

C++ 如何在编译时接受任意长度的对列表?

[英]C++ how to accept arbitrary length list of pairs at compile time?

I'm looking to build a compile-time read only map and was hoping to back it with a std::array or std::tuple where each element is a std::pair .我正在寻找构建一个编译时只读 map 并希望用std::arraystd::tuple支持它,其中每个元素都是一个std::pair For ease of use, I would like to avoid having to annotate every entry at construction, and I'd like it to deduce the number of elements in the map ie:为了便于使用,我想避免在构造时对每个条目进行注释,并且我希望它能够推断出 map 中的元素数量,即:

constexpr MyMap<int, std::string_view> my_map{
  {1, "value1"},
  {2, "value2"},
};

I've tried a number of strategies to do this, but I seem to be getting stuck in making a ctor or function that is able to both accept an arbitrary number of elements and also tell the compiler that all the braced entries being passed (ex {1, "value1"} ) is a pair, otherwise it cannot deduce the type.我已经尝试了多种策略来做到这一点,但我似乎陷入了制作一个既能接受任意数量的元素又能告诉编译器所有大括号条目都被传递的 ctor 或 function 中(例如{1, "value1"} ) 是一对,否则无法推断类型。

For example:例如:

template <typename Key, typename Mapped, typename... Args>
constexpr auto make_map(std::pair<Key, Mapped>&& first, Args&&... args) {
  if constexpr (sizeof...(Args) == 0) {
    return std::tuple{std::forward<decltype(first)>(first)};
  }
  return std::tuple_cat(
    std::tuple{std::forward<decltype(first)>(first)},
    make_map(std::forward<Args>(args)...)
  );
}

It seems like I could make a macro that would quickly allow me to make versions of the function for say all arguments up to a reasonable number (say 10-15) but this feels uglier and worse.似乎我可以制作一个宏,它可以让我快速制作 function 的版本,例如所有 arguments 到一个合理的数字(比如 10-15),但这感觉更丑陋和更糟。

Is there a way to do what I want, or do I need to resort to macros or making users annotate each entry with std::pair ?有没有办法做我想做的事,还是我需要求助于宏或让用户用std::pair注释每个条目?

If I am understanding correctly, the size of map is known and fixed?如果我理解正确,map 的大小是已知且固定的? If so, why not use a regular c-style array constructor?如果是这样,为什么不使用常规的 c 风格的数组构造函数呢? Unfortunately, there is no way to make the compiler deduce the type of direct initialization lists (ex: deduce {1, "value"} to std::pair<int, std::string_view> ) So, you have to specify the type for deduction to work.不幸的是,没有办法让编译器推断出直接初始化列表的类型(例如:将{1, "value"}推断为std::pair<int, std::string_view> )所以,您必须指定类型扣除工作。

#include <array>
#include <string_view>
#include <utility>

template <typename K, typename V, size_t N>
class MyMap {
 public:
  using value_type = std::pair<K, V>;

  constexpr explicit MyMap(value_type(&&init)[N])
      : data_(std::to_array(std::forward<value_type[N]>(init))) {}

  const std::array<value_type, N> data_;
};

template <typename K, typename V, size_t N>
constexpr MyMap<K, V, N> MakeMyMap(
    typename MyMap<K, V, N>::value_type(&&init)[N]) {
  return MyMap{std::forward<typename MyMap<K, V, N>::value_type[N]>(init)};
}

int main(int argc, char* argv[]) {
  constexpr std::string_view value_1 = "value1";
  constexpr std::string_view value_2 = "value2";

  constexpr auto my_map = MakeMyMap<int, std::string_view>({
      {1, value_1},
      {2, value_2},
  });

  static_assert(my_map.data_.at(0) == std::make_pair(1, value_1));
  static_assert(my_map.data_.at(1) == std::make_pair(2, value_2));

  return EXIT_SUCCESS;
}

Note: this is c++20 only because of std::to_array ( https://en.cppreference.com/w/cpp/container/array/to_array ).注意:这只是c++20 ,因为std::to_arrayhttps://en.cppreference.com/w/cpp/container/array/to_array )。 But one can easily implement that in c++17但是可以在c++17中轻松实现

#include <array>
#include <cstddef>
#include <type_traits>
#include <utility>

namespace internal {

template <bool Move = false, typename T, std::size_t... I>
constexpr std::array<std::remove_cv_t<T>, sizeof...(I)> to_array_impl(T (&a)[sizeof...(I)], std::index_sequence<I...>) {
  if constexpr (Move) {
    return {{std::move(a[I])...}};
  } else {
    return {{a[I]...}};
  }
}

}  // namespace internal

template <typename T, std::size_t N>
constexpr std::array<std::remove_cv_t<T>, N> to_array(T (&a)[N]) noexcept(
    std::is_nothrow_constructible_v<T, T&>) {
  static_assert(!std::is_array_v<T>);
  static_assert(std::is_constructible_v<T, T&>);
  return internal::to_array_impl(a, std::make_index_sequence<N>{});
}

template <typename T, std::size_t N>
constexpr std::array<std::remove_cv_t<T>, N> to_array(T(&&a)[N]) noexcept(
    std::is_nothrow_move_constructible_v<T>) {
  static_assert(!std::is_array_v<T>);
  static_assert(std::is_move_constructible_v<T>);
  return internal::to_array_impl<true>(a, std::make_index_sequence<N>{});
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM