5

I defined a function:

void myfunc(size_t param1, size_t param2){
...
}

it works fine. But when I try to overload this function

void myfunc(unsigned long param1, unsigned long param2){
...
}

It fails to compile with the following message: error: myfunc(unsigned long param1, unsigned long param2) cannot be overloaded.

How can I solve this problem without staic_cast the input parameters to size_t?

thanks!

M.M
  • 138,810
  • 21
  • 208
  • 365
Harvey Dent
  • 327
  • 2
  • 14
  • Did you mean to tag this C++? – Paul Roub Apr 30 '15 at 00:05
  • That's probably because `size_t` is defined as `unsigned long` on your environment. C/C++ doesn't have a very strong type system in this aspect. – Mysticial Apr 30 '15 at 00:06
  • 2
    This is a bad idea anyway because even if it worked, you would get ambiguous call errors whenever you tried to use the function with `int`s for example. Can you explain what problem you are trying to solve? – M.M Apr 30 '15 at 00:15
  • thank you all. Actually it passed the compilation, but failed at link phase, where a marco call myFunc(). – Harvey Dent Apr 30 '15 at 01:15

1 Answers1

3

It sounds like size_t and unsigned long are the same type on your system; the compiler is complaining that you have two of the same function. Furthermore, overloading with multiple number types is generally a bad idea because the compiler may not be able to recognize which overload you want due to casting possibilities. Try using templates instead:

template <T>
void myfunc(T param1, T param2){
...
}
sabreitweiser
  • 643
  • 3
  • 13
  • isn't size_t an unsigned integer? it can be unsigned int32 or unsigned int64 but can it be unsigned long? – mhs Apr 30 '15 at 00:28
  • 1
    @mhs the terminology can get a bit confusing; int, long, int32_t, uint32_t, etc... are all integer types. As far as I know, they're usually typedef'd down to the basic types, e.g. int or unsigned long. The difference is that the basic types are guaranteed by the standard to be AT LEAST a certain size, while the intX_t types are guaranteed to be EXACTLY X size. So, if you're on a system where long is a 64 bit data type, uint64_t might just be unsigned long. Similarly, if you're working on a 64 bit system, size_t might just be typedef'd to unsigned long as well. – sabreitweiser Apr 30 '15 at 00:34
  • thank you all. Actually it passed the compilation, but failed at link phase, where a marco call myFunc(). – Harvey Dent Apr 30 '15 at 01:15