需要帮助解决错误 C2664

Require Help Resolving error C2664

本文关键字:错误 C2664 解决 帮助      更新时间:2023-10-16

我有以下代码给我这个错误

main.cpp(41): 错误 C2664:"std::p air std::make_pair(_Ty1,_Ty2)":无法将参数 1 从"句柄"转换为"无符号 int &"

我的示例程序是

#include <vector>
#include <utility>
typedef unsigned int u32;
typedef u32 Handle;
struct File
{
    File()
        : ch(0),
        pageIdx(0)
    {
    }
    Handle ch : 8;
    u32 pageIdx;
};
int main() {
    std::vector<std::pair<Handle, u32> > toTrim;
    toTrim.reserve(64);
    File* m_pFirstPage = new File();
    File* pRef = m_pFirstPage;
    toTrim.push_back(std::make_pair(pRef->ch,pRef->pageIdx));
    return 0;
}

当我尝试静态投射时,即

toTrim.push_back(std::make_pair(static_cast<unsigned int>(pRef->ch), pRef->pageIdx));

我收到以下错误

main.cpp(41): 错误 C2664:"std::p air std::make_pair(_Ty1,_Ty2)":无法将参数 1 从"无符号 int"转换为"无符号 int &"

有人可以帮我解决它并解释我做错了什么。

正在发生的事情是,您正在使用: 8表示法指定位字段。

更多信息请见: http://www.tutorialspoint.com/cprogramming/c_bit_fields.htm

这会在句柄变量上创建一个 8 位的伪字符字段,而不是typedef u32 Handle定义的 32 位。 std::make_pair需要通过引用传递其参数。

由于Handle ch : 8的类型与Handle不同,因此不能通过引用传递它,因为被视为未定义的行为,通过引用传递的变量。

更多信息请见: 如何强制转换变量成员以将其作为函数的引用参数传递

如果您需要: 8字段,您可以使用额外的变量来正确创建对。

#include <vector>
#include <utility>
typedef unsigned int u32;
typedef u32 Handle;
struct File
{
    File()
    : ch(0),
    pageIdx(0)
    {
    }
    Handle ch : 8; //Different type than just Handle
    u32 pageIdx;
};
int main() {
    std::vector<std::pair<Handle, u32> > toTrim;
    toTrim.reserve(64);
    File* m_pFirstPage = new File();
    File* pRef = m_pFirstPage;
    unsigned int ch_tmp = pRef->ch; //<-Extra variable here
    toTrim.push_back(std::make_pair(ch_tmp, pRef->pageIdx));
    return 0;
}