我有下面的代码,给出了这个错误
main.cpp(41):C2664:‘std::对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):error C2664:‘std::结对std::make_pair(_Ty1,_Ty2)’:无法将参数1从“无符号int”转换为“无符号int&”
有人能帮我解决这个问题并解释我做错了什么吗?
发布于 2015-03-12 03:09:56
正在发生的事情是使用: 8符号指定位字段。
更多信息请访问:fields.htm
这将在句柄变量8位上创建一个伪char字段,而不是typedef u32 Handle定义的32位。std::make_pair需要通过引用传递它的参数。
由于Handle ch : 8是与Handle不同的类型,所以不能通过引用传递它,因为它被认为是未定义的行为,它强制转换了一个通过引用传递的变量。
更多信息请访问:How to cast a variable member to pass it as reference argument of a function
如果您需要: 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;
}https://stackoverflow.com/questions/29000895
复制相似问题