C++ 多态运算符[]实现
假设我们有以下代码:C++ 多态运算符[]实现,c++,C++,假设我们有以下代码: class test_t { void* data; public: template <typename T> T operator [](int index) { return reinterpret_cast<T*>(data)[index]; } }; int main() { test_t test; int t = test.operator []<int&g
class test_t
{
void* data;
public:
template <typename T>
T operator [](int index)
{
return reinterpret_cast<T*>(data)[index];
}
};
int main()
{
test_t test;
int t = test.operator []<int>(5);
return 0;
}
即多态运算符[]。您可以做的是返回代理对象
struct Proxy {
template<typename T>
operator T() {
return static_cast<T*>(data)[index];
}
void *data;
int index
};
Proxy operator [](int index)
{
Proxy p = { data, index };
return p;
}
struct代理{
模板
算子T(){
返回静态_cast(数据)[索引];
}
作废*数据;
整数索引
};
代理运算符[](整数索引)
{
Proxy p={data,index};
返回p;
}
您可以求助于
obj.get(index)
或类似的方法 那不是多态性。@SLaks:当然是多态性的一种。耶,太好了。这似乎真的很有效,我将初始值设定项风格的init替换为代理的构造函数,并使用reinterpret_cast,但它确实有效!谢谢,哎呀。在原始代码中,数据被视为一个T数组。在上面,用户索引i
选择sizeof(T)
字节,从数据的i
第个字节开始…@Alf ohh!杰出的Lemme修复它实际上,我需要将索引作为字节偏移量处理到缓冲区中,所以原始版本就可以了。
struct Proxy {
template<typename T>
operator T() {
return static_cast<T*>(data)[index];
}
void *data;
int index
};
Proxy operator [](int index)
{
Proxy p = { data, index };
return p;
}