Sturm
Sturm

Reputation: 4125

Template abuse?

I wanted to transform the dynamic_casts from base class to derived from this style:

auto derived = dynamic_cast<Derived*>(object);

To something more compact. For that I have added in Base class the following template:

template<typename T>
T As() { return dynamic_cast<T>(this); }

So now the previous statement would be rewritten as

auto derived = object->As<Derived*>();

I like this style more. But I know there might be readability issues (subjective) or memory usage of the class maybe? If am I correct this will generate a function for each type of derived I cast. This number can be potentially large (100 different derived classes).

Should I just stick to plain dynamic_cast?

Upvotes: 1

Views: 1017

Answers (1)

Peter
Peter

Reputation: 36607

If you read material from a number of experts who have participated in the design of C++ (Stroustrup, Sutter, the list goes on) you will find that dynamic_cast (and all the _casts) are verbose and clumsy for the programmer BY DESIGN.

Where at all possible, it is considered best to AVOID using them. While all of the _cast operators have their place (i.e. there are circumstances in which they are genuinely the best solution to a problem) they are also blunt instruments that can be used to work around problems due to bad design. Unfortunately, given a choice, a lot of programmers will reach for such blunt instruments rather than applying a bit more effort to learn appropriate techniques, and to clean up their design - which has benefits such as making the code easier to get working right, and easier to maintain.

dynamic_cast is, arguably, the worst of the _cast operators, since it almost invariably introduces an overhead at run time. If it is used to work around deficiencies due to bad design, there is a distinct run-time penalty.

Making the syntax clumsy and verbose encourages a programmer to find alternatives (e.g. design types and operations on types, in a way that avoids the need for such conversions).

What you're asking for is a way to allow programmers to use dynamic_cast easily and with less thought. That will encourage bad design, by allowing a programmer to easily use the _cast operators to work around design problems, when they would often be better off applying a bit more effort to avoid a need for such conversions in the first place. There is plenty of information available about techniques that can be used to avoid use of operations like dynamic_cast.

So, yes, if you really need to use such conversions, I suggest you stick to use of dynamic_cast.

Better yet, you might want to also apply effort to learn design techniques and idioms that reduce how often you need to use it.

Upvotes: 2

Related Questions