Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ proper way to static_cast

static_castwill not throw an exception. But if it does not succeed, it will produce a undefined result. What is the most proper way to check whether the cast succeeded?

Will this help?

NewType new_typ_obj = static_cast<NewType>(obj); 

if (new_typ_obj)
    new_typ_obj.do();
like image 826
kiriloff Avatar asked Apr 22 '13 12:04

kiriloff


People also ask

What is static cast in C++?

C++ Server Side Programming Programming. The static_cast is used for the normal/ordinary type conversion. This is also the cast responsible for implicit type coercion and can also be called explicitly. You should use it in cases like converting float to int, char to int, etc. This can cast related type classes.

What is the use of cast in C++?

This is also the cast responsible for implicit type coercion and can also be called explicitly. You should use it in cases like converting float to int, char to int, etc. This can cast related type classes. If the types are not same it will generate some error.

Can You static_cast from a pointer to an object?

You can't static_cast between references (or pointers) to "unrelated types." While you could static_cast from a CMyObject* to a CObject*, that isn't what you're doing here.

What is a C-style cast?

C casts are casts using (type)object or type (object). A C-style cast is defined as the first of the following which succeeds: const_cast static_cast (though ignoring access restrictions) static_cast (see above), then const_cast reinterpret_cast reinterpret_cast, then const_cast


1 Answers

static_cast does not give you information about success. If you need to do dynamic type casting use dynamic_cast or a library like boost any.

like image 188
rerun Avatar answered Sep 21 '22 23:09

rerun