views:

1221

answers:

2

I need to have a set of overloaded functions in my code but I get convertion wanrings. Here is a test code:

#include windows.h

void f(DWORD arg){...}

//void f(SIZE_T arg){}

void main(void)
{
DWORD dword=0;
SIZE_T size_t=dword;
f(size_t);

}

The compiler gives warning:

test.cpp(11) : warning C4244: 'argument' : conversion from 'SIZE_T' to 'DWORD', possible loss of data

If I uncomment void f(SIZE_T arg) I get

test.cpp(5) : error C2084: function 'void f(DWORD)' already has a body

How can I avoid having this warning or error?

+5  A: 

size_t is guaranteed to be an unsigned integral type, but the number of bits it has isn't specified. It could be equal to a DWORD (32 bits), or it could be 64 bits on a 64-bit platform. For maximal portability, you shouldn't assume it has a certain number of bits, which is what the compiler is warning you about. If you know your value will never exceed 2^32 (which is a reasonable assumption in 99.99% of cases), then you can just cast to a DWORD to get rid of the warning:

SIZE_T sz = dword;
f((DWORD)sz);  // no warning here

The error you're getting is because in your case, size_t is actually 32 bits, and so the function signatures of your two f functions are identical - they both take a single unsigned 32-bit parameter. You'll have to use separate names for them in order to guarantee that your program is portable between 32- and 64-bit platforms:

void f_DWORD(DWORD arg) { ... }
void f_size_t(size_t arg) { ... }

One final note: size_t is a built-in type. SIZE_T is non-standard and is almost definitely a typedef or a #define for size_t. You should use size_t instead of SIZE_T, and you should also avoid naming your variables size_t, since that introduces confusion by shadowing a type name with a variable name.

Adam Rosenfield
A: 

The simplest answer is to get rid of f(DWORD) and redefine it f(size_t). Unless, of course, f() operates on values other than size_ts.

Max Lybbert