4
votes

I have the following code which is giving me this error

main.cpp(41): error C2664: 'std::pair std::make_pair(_Ty1,_Ty2)' : cannot convert argument 1 from 'Handle' to 'unsigned int &'

My example program is

#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;
}

When I try to static cast i.e

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

I get the following error

main.cpp(41): error C2664: 'std::pair std::make_pair(_Ty1,_Ty2)' : cannot convert argument 1 from 'unsigned int' to 'unsigned int &'

Can someone please help me resolve it and explain what I am doing wrong.

1
I don't think it likes the bitfield. Why not use an 8-bit integer if that's what you want? Also why do you dynamically allocate the file object?Neil Kirk
Deleted my answer as I think this might be a compiler issue, your version with static_cast works fine for me on GCC 5, what compiler are you using?user657267
for the error notation "C2664" I would say VC++felknight
i am running the code on Microsoft visual studio Professional 2013bourne
do you need ": 8" notation? with out it, it compiles correctlyfelknight

1 Answers

0
votes

What is happening is that you are specifying bit fields with the : 8 notation.

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

That creates a pseudo-char field on your handle variable of 8 bits instead of 32 as typedef u32 Handle defines. std::make_pair requires passing it's arguments by reference.

Since Handle ch : 8 is different type from Handle you can't pass it by reference because is considered undefined behavior cast a variable that is pass by reference.

More info at: How to cast a variable member to pass it as reference argument of a function

If you need the : 8 field you may use an extra variable to create the pair correctly.

#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;
}