c++ - 重载元组索引运算符 - C++

标签 c++ indexing tuples operator-overloading std

如何重载索引 [] std::tuple<int,int,int> 的运算符?所以当我有 std::tuple<int,int,int> tup然后我输入 tup[0]我希望它返回对 get<0>(tup) 的引用.这可能吗?

最佳答案

如其他答案中所述 - 无法将任何成员函数添加到 std 类型,如 std::tuple。并且 operator[] 必须是非静态成员函数。

但是您可以包装这个元组 - 并将 operator[] 添加到这个包装器类型。在这种情况下——您需要知道元组所有元素的通用返回类型。好吧 - std::any 可以适用于大多数类型。

这应该可行,但这只是为了满足您的好奇心——在实际软件中使用类似的东西将是糟糕的设计:

template <typename Tuple, typename ReturnType = std::any>
class TupleExtractor
{
public:
    TupleExtractor(const Tuple& tuple) 
        : TupleExtractor(tuple, std::make_index_sequence<std::tuple_size_v<Tuple>>{})
    {}
    
    ReturnType operator[](std::size_t index) const
    {
        return extractors[index](tuple);
    }

private:
    template <std::size_t I>
    static ReturnType get(const Tuple& tuple)
    {
        return std::get<I>(tuple);
    }


    template <std::size_t ...I>
    TupleExtractor(const Tuple& tuple, std::index_sequence<I...>) 
        : tuple(tuple), 
          extractors{&TupleExtractor::get<I>...}
    {}

    const Tuple& tuple;
    using Extractor = std::any(*)(const Tuple&);
    std::vector<Extractor> extractors;
};

并测试它是否有效:

int main() {
    std::tuple<int, int, int> a{1,2,3};
    TupleExtractor e{a};
    
    return std::any_cast<int>(e[2]);
}

关于c++ - 重载元组索引运算符 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62852758/

相关文章:

python - 如何使用 Pandas 映射嵌套在字典中的元组的索引?

.net - .NET Framework 上的许可证是否允许分发其代码的派生形式?

c++ - 是否可以用 gcc 编译 c++ 代码?

python - 获取一个列表并打印所有不等于 0 的元素的索引

python - 元组部分匹配

元组的 Python 列表将第二个元素与唯一的第一个元素合并

c++ - 将字符串转换为 TDateTime 变量

c++ - 使用不匹配单词的正则表达式链捕获

jquery - 获取 ul 中 li 的索引

sql - Postgres 不使用索引,即使返回的行少于 5%