c++ - 实现接受索引数组的下标运算符

标签 c++ arrays templates variadic-templates c++17

这是我的问题 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>{});
}

See it live on Coliru

关于c++ - 实现接受索引数组的下标运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48006132/

相关文章:

java - 如何为 Map of Sets 的 Java Map 声明 TypeScript 类型?

c++ - 如何在 OpenGL 中叠加文本

c++ - 位在字节顺序中重要吗?

c++ - 为什么调用 GC.Collect 会加快速度

c++ - 使用 Hoare 分区方案的快速排序算法返回原始未排序列表

c - 未初始化字符数组的 %d 说明符

arrays - Perl 关联数组和变量赋值

powershell - Azure Powershell 模板 : return Boolean if all resource provisioned successfully?

依赖于特定类类型的 C++ 模板方法?

c++ - 为什么函数模板调用类模板的静态方法模板会编译失败?