gpt4 book ai didi

c++ - 通过派生模板类的正确类型转换从基类访问数据

转载 作者:行者123 更新时间:2023-11-30 05:18:48 24 4
gpt4 key购买 nike

我有以下场景:

class ScalarField
{
void* _buffer; //Array for data.
};

派生类:

template <typename T> 
class ScalarFieldT : public ScalarField
{
ScalarFieldT(int size)
{
_data = new T[size];
_buffer = _data;
}

T& get(int index)
{
return _data[index];
}

T* _data; // Typed array for data
};

请注意,T 只能采用基本类型,如 float、int、double 等。

这是一个非常古老的遗留代码,所以我没有太多的灵 active 来适本地调整它来做一个更好的设计。需要做的是访问来自 ScalarField::_buffer 的数据,并对其派生类进行正确的类型转换。

像这样:

void main()
{
int n = TOTAL_SIZE;
ScalarFieldT<int> typedScalarField(n);

ScalarField* scalarField = &typedScalarField;

// This is what I need to do:
int index = ELEMENT_INDEX;
float value = scalarField->method(index); // Get the value from base class correctly converted from int to float, for example.
}

关键是,我只能访问基类抽象,但我需要从 _buffer 中获取值并将其转换为另一种简单的数据类型,例如 float、int、uchar 等。

你们有什么推荐的?

提前致谢!

最佳答案

您可以使用提供一组转换运算符的类型作为方法的返回类型。
它遵循一个最小的工作示例:

#include<memory>

class ScalarField {
protected:
struct Value {
virtual operator float() const = 0;
virtual operator int() const = 0;
// ...
};

public:
virtual const Value & method(int i) = 0;

protected:
void* buffer;
};

template <typename T>
class ScalarFieldT : public ScalarField {
struct TValue: Value {
TValue(T value): value{value} {}
operator float() const override { return float(value); }
operator int() const override { return int(value); }
// ...

private:
T value;
};

public:
ScalarFieldT(int size) {
data = new T[size];
buffer = data;
}

T& get(int index) {
return data[index];
}

const Value & method(int i) {
std::make_unique<TValue>(data[i]);
}

private:
std::unique_ptr<Value> value;
T* data;
};

int main() {
ScalarFieldT<int> typedScalarField(10);
ScalarField* scalarField = &typedScalarField;
float f = scalarField->method(2);
int i = scalarField->method(5);
}

关于c++ - 通过派生模板类的正确类型转换从基类访问数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41433780/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com