首页 > 解决方案 > 如果字节缓冲区应该是无符号字符,我是否必须一直保持转换?

问题描述

根据这些答案,字节缓冲区应该是无符号字符,无论是因为约定还是填充保证,我都不确定。我有一个看起来像这样的函数:

saveDataToFile(const unsigned char* data, size_t size);

我发现当我有一个 char 向量或 std::string 或字符串文字或其他东西时,我一直不得不进行转换,而我的代码最终看起来像:

const char* text = "text";
saveDataToFile(text, 4); // Argument of const char* is incompatible with parameter of type const unsigned char*
saveDataToFile(reinterpret_cast<const unsigned char*>(text), 4);

有没有办法避免一直这样做?有人曾经提到让我的函数采用 const char* 而不是 unsigned,但这并不是真的,因为那时我必须采用另一种方式。例如 std::string 具有返回有符号和无符号的 .c_str() 和 .data()。我也想过服用void*,也许这是最好的方法?

标签: c++

解决方案


正如您自己建议的那样,也许最简单const void*的方法是使函数的第一个参数 a ,然后将其强制转换为函数内部所需的任何内容。这样,您还可以避免使用 areinterpret_cast并且可以安全地使用 a static_cast

void saveDataToFile(const void* data, size_t size)
{
    const uint8_t* local = static_cast<const uint8_t*>(data);
    //.. do something with the cast pointer ...
}

int main()
{
    double dData = 33.3;
    int16_t sData = 42;
    char cData[] = "Hello, World!";

    saveDataToFile(&dData, sizeof(dData));
    saveDataToFile(&sData, sizeof(sData));
    saveDataToFile(cData, sizeof(cData));

    return 0;
}

一种更“纯 C++”的方式(在某些人看来,也许是)是制作一个模板函数。但是,这里的缺点是:(a)在这种情况下您将需要a ;reinterpret_cast(b) 编译器将(可能)为使用的每种不同的参数类型生成单独的函数代码:

template<typename T>
void saveDataToFile(const T* data, size_t size)
{
    const uint8_t* local = reinterpret_cast<const uint8_t*>(data);
    //.. do something with the cast pointer ...
}

推荐阅读