我有一个集合类,它需要使用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[]()方法中做更多的工作。
发布于 2014-10-28 17:30:19
听起来你可以使用尾随返回值类型推导,尽管我可能完全误解了你。
auto operator[](int i) -> decltype(collection[i]) {
return collection[i];
}然后由编译器来推断返回类型,但是,当然,您不能(在运行时)返回可变类型。就像你不能(安全地)将它们存储在一个集合中一样
https://stackoverflow.com/questions/26600798
复制相似问题