views:

216

answers:

4

Hello all!

How do i check if a result is of the right type(int, float, double, etc.) and then throw and catch an exception in case it's not?

Thanks all,

Vlad.

+4  A: 

There is no way to know that at runtime with C++. These would be compile-time errors.

To answer your second question, you have to manually check for buffer overflows/underflows or use a more appropriate datatype.

Daniel A. White
+1, but it's exactly the opposite - there's almost no way *not* to know that at runtime, because otherwise code wouldn't compile ;-)
Michael Krelin - hacker
Except when using a template instance, where the template parameter can be any class/type at all, even one that didn't exist when the template was written.
suszterpatt
But templates are not at runtime. They are generated at compile-time too.
Daniel A. White
It all depends on what he is getting this result from. If it is a pointer to something cast as a void* that he is getting from somewhere else you would not know it's true type unless you were told.
Adam W
A: 

The closest you'll get is dynamic_cast.

Matthew Iselin
dynamic_cast doesn't work for built-in types. It works only for references/pointers to polymorphic types.
Cătălin Pitiș
Which is why I said the *closest* you'll get is dynamic_cast (not "the answer is dynamic_cast", note the difference). I mentioned dynamic_cast because I wasn't sure if the OP was asking for *just* builtins or for a larger set of types.
Matthew Iselin
+4  A: 

Could you give more detail about what is giving you "a result" you may be able to determine what you need from there and more likely in a better way.

If all you really want is to check the type, use typeid. More info here

Following Daniel's model of editing posts to actually answer the question after stating something else...

From my other comment:

You have to do this BEFORE you have just the result. Checking for overflow after is not a good idea. Do a check on the numbers before adding to see if they will overflow, or restrict input to be less than half the max value of the type

Adam W
Thanks for your answers, Adam.
Vlad
A: 

Well to make it simple, let's say I have two numbers and after adding them or any other operation the result is bigger or low than the int range. So there any way to throw and catch an exception when the result gets out of bounds?

Vlad
Please edit your original post. Don't add an answer.
Daniel A. White
You have to do this BEFORE you have just the result. Checking for overflow after is not a good idea. Do a check on the numbers before adding to see if they will overflow, or restrict input to be less than half the max value of the type.
Adam W
I see, so there's no other than this?
Vlad
See my answer about typeid for ways to check type in other situations, but I think in your case you will have to do it before just having the result.
Adam W