Static_cast for custom types

Is it possible, and why do it?

class Foo; class Bar; ...... Foo foo; Bar bar = static_cast<Bar>(foo); 

Normally static_cast is used with numeric types and pointers, but can it work with user-defined data types, aka classes?

+6
source share
2 answers
 Bar bar = static_cast<Bar>(foo); 

This cast will fail. Foo and Bar are incompatible types, if only at least one of the following statements:

  • Foo sourced from Bar , Or
  • Bar has a constructor that accepts Foo , Or
  • Foo has a custom conversion to Bar .

The big question here is not whether it will be issued successfully or not. The bigger and more relevant question should be: what do you want to get out of such an actor? Why do you do this in the first place? What should he do? I mean, how would a Bar object be initialized from a Foo object?

A reasonable way to convert one type to another is one of the following methods:

Define Foo as:

 class Foo : public Bar { //... }; 

Or define Bar as:

 class Bar { public: Bar(const Foo &foo); //define this constructor in Bar! }; 

Or provide a conversion function in Foo like:

 class Foo { public: operator Bar(); //provide a conversion function Foo to Bar! }; 
+10
source

Here's the rule:

The expression static_cast<T>(e) valid if and only if the following definition of a variable is true

 T x(e); 

where x is some invented variable.

Thus, in the general case, two unrelated types cannot be dropped to each other. However, if one type is derived from another or when it defines a function for converting to another or has a constructor that takes one argument of another type, in these cases static_cast will be well defined.

Does it ever make sense? For example, if T defines a constructor that takes one U and an explicit constructor, then static_cast<T>(e) , where e is of type U, will make perfect sense

+11
source

Source: https://habr.com/ru/post/896669/


All Articles