[英]Construct an array of indices of std::tuple types
給定一個包含不同類型元素的元組(沒有兩個是相同的):
typedef std::tuple<bool, char, int, float, double, std::string> t1;
以及包含限制為這些類型的元素的元組類型(重復和遺漏是可能的,但沒有其他類型):
typedef std::tuple<char, int, int, double, std::string, int, double> t2;
如何為t2
的元素構造一個std::array
其中包含t1
匹配元素的索引?
{1, 2, 2, 4, 5, 2, 4}
當然,這是可行的。
讓我們對std::integer_sequence
、 std::tuple
和相關機制進行鍛煉。
首先,編寫一種方法來獲取類似元組的任意類型的單個唯一匹配項的索引:
template <class T, class U, std::size_t... N>
static constexpr auto tuple_index_impl(std::index_sequence<N...>) noexcept {
static_assert((std::size_t() + ... + std::is_same_v<T, std::tuple_element_t<N, U>>) == 1,
"There is no single exact match");
return (0 + ... + (N * std::is_same_v<T, std::tuple_element_t<N, U>>));
}
template <class T, class U>
static constexpr std::size_t
tuple_index_v = tuple_index_impl<T, U>(std::make_index_sequence<std::tuple_size_v<U>>());
可惜這不是標准庫的一部分。
接下來,使用它來獲取所有索引並將它們放入std::array
:
template <class T, class U, std::size_t... N>
constexpr auto indices_impl(std::index_sequence<N...>) noexcept {
return std::array<std::size_t, sizeof...(N)>{tuple_index_v<std::tuple_element_t<N, U>, T>...};
}
template <class T, class U>
constexpr auto indices() noexcept {
return indices_impl<T, U>(std::make_index_sequence<std::tuple_size_v<U>>());
}
使用示例:
for (auto x : indices<t1, t2>())
std::cout << x << '\n';
在coliru上看到它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.