这是我的问题 Implement STL functions in variadic template 的延续:
如果已经定义了“单层”下标,我如何为接受长度为 N
的数组的 N
维数组实现下标运算符用作 array[indx0][indx1]…[indxN]
的运算符。我觉得应该有一个简单的折叠表达式吗?
最佳答案
因此,[]
不是可折叠运算符之一。无赖。但我们只需要作弊并搭载另一个 :)
namespace indexer_detail {
template <class T>
struct ArrayWrapper {
T obj;
};
template <class T>
ArrayWrapper(T&&) -> ArrayWrapper<T&&>;
template <class T>
auto operator & (ArrayWrapper<T> const &aw, std::size_t N) {
return ArrayWrapper{aw.obj[N]};
}
}
template <std::size_t Size, class Array, std::size_t... Idx>
decltype(auto) index(
Array &&array,
std::array<std::size_t, Size> const &indices,
std::index_sequence<Idx...>
) {
return (
indexer_detail::ArrayWrapper{std::forward<Array>(array)} & ... & indices[Idx]
).obj;
}
template <std::size_t Size, class Array>
decltype(auto) index(Array &&array, std::array<std::size_t, Size> const &indices) {
return index(std::forward<Array>(array), indices, std::make_index_sequence<Size>{});
}
关于c++ - 实现接受索引数组的下标运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48006132/