这是我的问题在可变模板中实现STL函数的延续
如何实现N-dimensional数组的下标操作符,该数组接受长度为N的数组,因为已经定义了要用作array[indx0][indx1]…[indxN]的“单层”下标运算符。我觉得这应该有一个简单的折叠表达吗?
发布于 2017-12-28 14:48:40
因此,[]不是折叠式运算符之一。真扫兴。但我们只需要稍微欺骗一下,然后再重复一次:)
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>{});
}在Coliru看现场直播
发布于 2018-10-06 06:16:09
因为它是C++17,所以如果要使它更简单,我们可以使用constexpr:
template<size_t Idx0, size_t... IdxRest, typename V>
decltype(auto) getval(const V& v)
{
if constexpr (sizeof...(IdxRest) == 0)
{
return v[Idx0];
}
else
{
return getval<IdxRest...>(v[Idx0]);
}
}
int main()
{
int arr[10][10] = { 1,2,3 };
std::vector<int> arr2 = { 1,2,3 };
auto v1 = getval<0, 2>(arr);
auto v2 = getval<1>(arr2);
return 0;
}https://stackoverflow.com/questions/48006132
复制相似问题