将模板typename转换为uint64

时间:2017-04-10 23:51:48

标签: c++ memory casting

我有这个函数读取内存,并返回指定地址的字符串(或驻留在内存中的任何类型)。但是我收到了错误:

error: invalid conversion from 'uint64_t to 'const char*'

我做错了什么?我以前就以这种方式看过它。这是我正在尝试做的代码:

template<typename T>
T ReadMemory(uint64_t addr, size_t size)
{
    uint64_t some_address = addr;
    size_t string_size = size;
    uint64_t return_value;
    //store address contents into return_value using driver

    //cast typename on return_value
    return (T)return_value;
}

int main()
{
    string foo = ReadMemory<string>(some_address,some_size);
}

2 个答案:

答案 0 :(得分:1)

注意:不要投射C风格

由于您使用的是C ++,因此应避免使用override func willBecomeActive(with conversation: MSConversation) { // Called when the extension is about to move from the inactive to active state. // This will happen when the extension is about to present UI. // Use this method to configure the extension and restore previously stored state. let val = conversation.selectedMessage?.url?.query?.description print("GOT IT ", val) if(val != nil) { scene.testTxt = val! } } 等C样式。有关类似C ++的版本,请参阅Why use static_cast(x) instead of (int)x?

现在让我们解决你的问题。

模板专业化

这个想法是为每个使用的泛型类型专门化一个模板。

您的标题可以包含

(type) value

并且您的实施包含

template<typename T>
T ReadMemory(uint64_t addr, size_t size);

依此类推您想要实现的所有类型。有关详细信息,请参阅How do I explicitly instantiate a template function?

C ++ 17解决方案

C ++ 17将添加一个名为/* type is std::string */ template<> std::string ReadMemory(uint64_t addr, size_t size){ uint64_t some_address = addr; size_t string_size = size; uint64_t return_value; //store address contents into return_value using driver //cast typename on return_value return std::to_string(return_value); } /* type is uint64_t */ template<> unit64_t ReadMemory(uint64_t addr, size_t size){ uint64_t some_address = addr; size_t string_size = size; uint64_t return_value; //store address contents into return_value using driver //cast typename on return_value return return_value; } 的惊人新功能。只要编译器支持这一点,您就可以像这样使用它:

if constexpr

答案 1 :(得分:0)

您无法将数字转换为std :: string。相反,使用C ++ 11中的std::to_string。例如,使用模板专业化:

template<>
std::string ReadMemory(uint64_t addr, size_t size)
{
    uint64_t some_address = addr;
    size_t string_size = size;
    uint64_t return_value;
    //store address contents into return_value using driver

    //cast typename on return_value
    return std::to_string(return_value);
}

template<>
std::wstring ReadMemory(uint64_t addr, size_t size)
{
    uint64_t some_address = addr;
    size_t string_size = size;
    uint64_t return_value;
    //store address contents into return_value using driver

    //cast typename on return_value
    return std::to_wstring(return_value);
}