具有模板成员变量和函数的类

时间:2017-12-07 20:31:57

标签: c++ class templates

我正在尝试创建这样的东西:

// The code doesn't work, it should just be a pseudo to help understand what i'm trying to create
template <typename Variable>
class Address
{
    unsigned int A_Address;
    Variable A_Type;

    void Set(A_Type value)
    {
        *((A_Type*)A_Address) = value;
    }

    A_Type Get()
    {
        return *((A_Type*)A_Address);
    }
};

Address address_1 = new Address<float/*type*/>(0x00000000/*address in memory*/);
address_1.Set(30.0f);
float value_1 = address_1.Get();

Address address_2 = new Address<int/*type*/>(0x00000000/*address in memory*/);
address_2.Set(10);
int value_2 = address_2.Get();

所以我希望能够定义Address obj_1, obj_2;之类的对象,然后使用类型和地址对它们进行初始化。然后Get()方法应该在内存中返回它的当前值,Set()方法应该在内存中设置该值。我无法弄清楚如何不使用Address<float> obj_1;而是使用Address obj_1;并稍后进行初始化。希望你能理解我想要做的事情,如果有可能的话可以让我知道,如果是这样的话,可能会帮助我或者指出我正确的方向。 提前谢谢!

1 个答案:

答案 0 :(得分:0)

我并没有真正处理你的地址错误,但你想要的是这样做的:

struct Address
{
Address(unsigned int addr)
: A_Address(addr)
{}

unsigned int A_Address;

template <typename T>
void Set(T value)
{
    *((T*)A_Address) = value;
}

template <typename T>
T Get()
{
    return *((T*)A_Address);
}
};

你可以这样使用

Address address(0x00000000);  //won't work because of virtual addressing
address.Set<float>(10.0F);
std::cout << address.Get<float>();

address.Set<double>(99.0);
std::cout << address.Get<double>();

当你以这种方式处理地址时要小心,非常容易出错。看看那边:

Pass a hex address to a Pointer Variable