Take a look at this: Stopping function implicit conversion
I was able to adapt it to your issue, and it stops the program from linking. The info in the above thread seems partially incorrect because the example compiled fine. It failed to link because there was not a template specialization defined. I'm actually a little surprised that the following worked for the int vs unsigned int.
template <class T>
void foo(const T& t);
template <>
void foo<unsigned int>(const unsigned int& t)
{
}
int main(){
foo((unsigned int) 9); // will compile and link
unsigned int value(5);
foo(value);// will compile and link
foo(9.0); // will not link
foo(-9); // will not link
return 0;
}
I think that you might be over thinking this though. Is it really a problem? Would it be better to make your id type an int to begin with? Is there a min/max id that avoids the large numbers that could be mistaken for a twos compliment? This seems like an unfortunate issue with the language that it doesn't provide any easy way to stop an implicit cast.
I tested the example with Visual Studio 2010. Additionally, I didn't have the time to write a test class so if it interests you then you'll have to adapt the example to a foo class to see if it works with a constructor of a class, or if there is another way to use templates to do this. Based on the other answers, and my experience I don't think that you are going to find an easy way to do what you want.
(-1, 0)
. Input a string, then convert it to an unsigned integer usingstrtoul()
. It will report an error if the number was negative. – Jejune1 << width
, wherewidth
is the number of bits in anunsigned int
. – Jejuneb = -1
to the function you should trigger the condition at start andexit
withEXIT_FAILURE
value. But the problem is that the input values defined asunsigned int
's which means that theb
will be equal to the maximum value available to theunsigned int
type on your system. Perhaps, the problem in something different than that? – Rianon