从重载运算符[](templates?)返回不同的类型

Return different types from overloaded operator[] (templates?)

本文关键字:返回 类型 templates 运算符 重载      更新时间:2023-10-16

我有一个集合类,它需要使用operator[]来访问其数据,但是返回的数据可以是许多不同的类型(从基类派生)。有没有一种方法可以使用模板,甚至其他一些不同的方法来重载返回不同类型的operator[]。如果可能的话,我们非常感谢示例或代码片段。

也许您正在寻找类似的东西

#include <vector>
#include <iostream>
template<typename ElementType>
class SpecialCollection
{
public:
    SpecialCollection(int length)
        : m_contents(length)
    {}
    ElementType& operator[](int index)
    {
        return m_contents[index];
    }
private:
    std::vector<ElementType> m_contents;
};
// Example usage:
int main()
{
    SpecialCollection<int> test(3);
    test[2] = 4;
    std::cout << test[1] << " " << test[2] << std::endl;
    return 0;
}

看着这段代码,我问自己:为什么不直接使用std::vector呢?但也许您想在operator[]()方法中做更多的工作。

听起来你可以使用尾随返回类型推导,尽管我可能完全误解了你。

auto operator[](int i) -> decltype(collection[i]) {
   return collection[i];
}

然后由编译器来推导返回类型,但是,当然,不能(在运行时)返回可变类型。正如您不能将它们(安全地)存储在一个集合中一样,