atoi()等效于intptr_t / uintptr_t

时间:2014-04-18 00:23:21

标签: c++ atoi string-conversion

C ++中是否有一个函数(C ++ 11,如果有所作为)将字符串转换为uintptr_tintptr_t?我总是可以使用atoll()然后将其强制转换,但是对于32位计算机和64位计算机的64位计算机来说,这样做会很好。

char* c = "1234567";
uintptr_t ptr = atoptr(c); // a function that does this;

1 个答案:

答案 0 :(得分:2)

这是IMO在C ++中令人惊讶的差距。 stringstream可以完成这项工作,但是对于完成这样一个简单的任务而言,它却是一个沉重的工具。相反,您可以编写一个内联函数,该函数根据类型大小调用strtoul的正确变体。由于编译器知道正确的大小,因此将其聪明地替换为对strtoul或strtoull的调用。即,如下所示:

    inline uintptr_t handleFromString(const char *c, int base = 16)
    {
         // See if this function catches all possibilities.
         // If it doesn't, the function would have to be amended
         // whenever you add a combination of architecture and
         // compiler that is not yet addressed.
         static_assert(sizeof(uintptr_t) == sizeof(unsigned long)
             || sizeof(uintptr_t) == sizeof(unsigned long long),
             "Please add string to handle conversion for this architecture.");

         // Now choose the correct function ...
         if (sizeof(uintptr_t) == sizeof(unsigned long)) {
             return strtoul(c, nullptr, base);
         }

         // All other options exhausted, sizeof(uintptr_t) == sizeof(unsigned long long))
         return strtoull(c, nullptr, base);
    }

如果您决定更改手柄的类型,这将很容易更新。如果您喜欢尖括号,您也可以做一些与模板等效的操作,尽管我不认为这会更清楚。