c++ - 操作内存的模板函数

标签 c++ templates memory

我正在修改游戏的内存,因此我做了这样的事情:

*(float*)0x89635637 = 10.0f;

现在我想把它变成一个模板函数,它允许我只写一次地址就可以读取和设置内存,我想到了这样的事情:

template <typename Variable> Variable GetSetAddress(Variable address, Variable value = NULL)
{
    if (value != NULL)
        *(Variable*)address = value;

    return *(Variable*)address;
}

现在我试着这样调用它:

float value = GetSetAddress<float>(0x89635637, 10.0f);

但它给了我这个错误:

error C2440: 'type cast' : cannot convert from 'float' to 'float *'

我对使用模板非常缺乏经验,所以如果你们中的任何一位能为我指出正确的方向,我将不胜感激。提前致谢!

最佳答案

valueNULL 进行比较没有意义,因为在这种情况下 value 是一个 float。另外,address参数不应该是Variable,它应该是一个可以存储指针值的整数类型,比如std::uintptr_t

template <typename T> T GetSetAddress(std::uintptr_t address, T value)
{
    *(T*)address = value;
    return *(T*)address;
}

通常最好也避免使用 C 风格的转换。您可以改用 reinterpret_cast,并简化返回语句:

template <typename T> T GetSetAddress(std::uintptr_t address, T value)
{
    *reinterpret_cast<T*>(address) = value;
    return value;
}

关于c++ - 操作内存的模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47695165/

相关文章:

c++ - 放置新的以推迟到不同的构造函数

c++ - 如何在静态函数中使用静态 vector

c++ - 模板函数中 const 引用的类型推导

python - Django 模板三元运算符

multithreading - 虚拟Listview,线程和内存消耗不下降

c++ - QT部署错误

c++ - 将 VAO 与 glDrawElements 结合使用

c++ - 在非实例化模板中使用 static_assert 的正确方法是什么?

C# 列表和内存

C-动态内存