我有一个集合类,它需要使用operator[]来访问它的数据,但是返回的数据可以是许多不同的类型(从基类派生)。有没有办法使用模板或者其他一些不同的方法来重载返回不同类型的operator[]。如果可能的话,非常感谢示例或代码片段。
发布于 2014-10-28 17:07:27
也许你正在寻找这样的东西
#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[]()方法中做更多的工作。
https://stackoverflow.com/questions/26600798
复制相似问题