首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从重载的operator[]返回不同的类型(模板?)

从重载的operator[]返回不同的类型(模板?)
EN

Stack Overflow用户
提问于 2014-10-28 12:15:11
回答 2查看 189关注 0票数 0

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

EN

Stack Overflow用户

发布于 2014-10-28 17:07:27

也许你正在寻找这样的东西

代码语言:javascript
复制
#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[]()方法中做更多的工作。

票数 1
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26600798

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档