需要帮助解决错误 C2664

Require Help Resolving error C2664

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

main.cpp(41): error C2664: 'std::pair std::make_pair(_Ty1,_Ty2)' : cannot convert argument 1 from 'Handle' to 'unsigned 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): error C2664: 'std::pair std::make_pair(_Ty1,_Ty2)' : cannot convert argument 1 from 'unsigned int' to 'unsigned int &'

谁能帮我解决这个问题并解释我做错了什么。

发生的情况是您使用 : 8 表示法指定位字段。

More info at: http://www.tutorialspoint.com/cprogramming/c_bit_fields.htm

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

由于 Handle ch : 8Handle 的类型不同,因此您不能通过引用传递它,因为它被认为是未定义的行为,会强制转换通过引用传递的变量。

More info at:

如果您需要 : 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;
}